S&box Wiki

Revision Difference

Player_Controller#543921

<cat>Code.Player</cat> <title>Player Controller</title> # What is a Player Controller A PlayerController takes input from the user and moves the player. # Example The simplest controller is a noclip controller. It moves the player relative to the direction they're facing. ``` public class NoclipController : PlayerController { public override void Tick() public override void Simulate() { // Face whichever way the player is aiming Rot = Input.Rot; Rotation = Input.Rotation; // Create a direction vector from the input from the client var direction = new Vector3( Input.Forward, Input.Right, 0 ); var direction = new Vector3( Input.Forward, Input.Left, 0 ); // Rotate the vector so forward is the way we're facing direction *= Rot; direction *= Rotation; // Normalize it and multiply by speed direction = direction.Normal * 1000; // Apply the move Pos += direction * Time.Delta; Position += direction * Time.Delta; } } ``` The PlayerController class has a number of persistent common properties such as Pos, Rot, Velocity, GroundEntity. <note>Setting these properties like Pos or Rot doesn't immediately change anything on the player. The new position is applied later. This means you can incrementally change these values and restore them without worry that you're going to leave the player in a weird state.</note> # Setting The Player Controller To set the player controller on a player you can set the Controller property. You can do this in Respawn, or the player's constructor. ``` public override void Respawn() { base.Respawn(); Controller = new NoclipController(); } ``` You can change this property at any point during the game to give the player a different controller. Or set it to null if you don't want the player to move. <note>You only need to set Controller serverside. The change will replicate to the client.</note> # Input ``` // // True if the button is down, but wasn't last tick // if ( Input.Pressed( InputButton.Jump ) ) { DoJump(); } // // True if the button is down // if ( Input.Down( InputButton.Walk ) ) { speed *= 0.4f; } // // The direction the player is aiming // var eyesForward = Input.Rot; // // Contain values from -1 to +1 describing how the player // wants to move. If you hold 'w' down, Forward = 1 // bool bWantsMove = Input.Forward != 0; bWantsMove = bWantsMove || Input.Right != 0; ``` # Do's and Don'ts The PlayerController shouldn't really ever access the player directly. It can, but it probably shouldn't. # Prediction The PlayerController is run on both the local client and the server. When the Client gets the results from the server, it compares them. If they don't match it snaps the client back to what the server said it should be. Your controller should always do exactly the same thing.