S&box Wiki

Revision Difference

Pawn_Input#551272

<cat>Code.Player</cat> To help operate your [Pawn](https://wiki.facepunch.com/sbox/Pawn) you might want to provide some special input data from the clientside. ## Client Input Properties You can mark properties on a [Pawn](https://wiki.facepunch.com/sbox/Pawn) or [Entity Component](https://wiki.facepunch.com/sbox/Entity_Components) with the `[ClientInput]` attribute. Properties with this attribute are automatically serialized and sent to the server. ## Building Input Every frame `BuildInput()` gets called clientside. The static `Input` class can be used to grab raw input data and then use that data to set any properties with the `[ClientInput]` attribute. ```csharp // An example BuildInput method within a player's Pawn class. [ClientInput] public Vector3 InputDirection { get; protected set; } [ClientInput] public Angles ViewAngles { get; set; } public override void BuildInput() { InputDirection = Input.AnalogMove; var look = Input.AnalogLook; var viewAngles = ViewAngles; viewAngles += look; ViewAngles = viewAngles.Normal; } ``` ## Simulate Every tick clients send a **Command** that contains the values constructed from BuildInput. This command then gets simulated in `Game.Simulate( Client )` for each client. Within Simulate( Client ) the static [Input](https://asset.party/api/Sandbox.Input) class contains inputs specific to the currently simulated client, this allows you to run the same code on both the server and client for [Prediction](Prediction). ```csharp // An example Simulate method within a player's Pawn class. public override void Simulate( Client cl ) public override void Simulate( IClient cl ) { if ( Input.Pressed( "jump" ) ) { Velocity += Vector3.Up * 100f; } Velocity += InputDirection * 400f; Rotation = ViewAngles.ToRotation(); } ``` ### Button State A `[ClientInput]` property can also be a `ButtonState`. This struct lets you treat an input as if it were a button, so that in Simulate you can get whether it was "pressed" or "released" or whether it is "down". This can make stuff like couch co-op easier. ```csharp [ClientInput] public ButtonState Jump { get; set; } public override void BuildInputs() { if ( IsPlayerOne ) Jump = Input.Down( "jump" ); else if ( IsPlayerTwo ) Jump = Input.Down( "drop" ); } public override void Simulate( Client client ) public override void Simulate( IClient client ) { if ( Jump.Pressed ) { Velocity += Vector3.Up * 100f; } } ```