Writing Client-Side Prediction code
Network Input
Network Input describes what the player wants to do, which will be used to simulate the state of objects they want to control. This ensures that the client can’t directly change the state – the change happens by executing the input, which, even if tampered with, won’t be game-breaking.
Defining Inputs
To define a new input, create a class that inherits from NetworkInput:
Setting Inputs
To set the variables of an input, you first need to acquire the input object of the next tick, using Sandbox.GetInput
.
Then, you can set it inside NetworkUpdate
on NetworkBehaviour:
You could also set them on OnInput
of NetworkEventsListner, which is preferred.
Simulating/Executing Inputs
To drive the gameplay based on the input object, you must do that in NetworkFixedUpdate
:
Don’t confuse Sandbox.GetInput with FetchInput. – Sandbox.GetInput is used to read/set the user inputs into the input object. – FetchInput is used to actually use the input object in the simulation.
FetchInput tries to fetch an input for the state/tick being simulated/resimulated. It only returns true if either:
We are providing inputs to this object – meaning we are the Input Source of the object.
We are the owner (the server) of this object – receiving inputs from the client who’s the Input Source. And only if we have an input for the current tick being simulated. If not, it would return false. Usually, that happens due to packet loss.
And to avoid the previous issue we talked about, we make sure that we are only shooting if we are simulating a new input, by checking IsResimulating
.
Input Source
For a client to be able to provide inputs to be used in an Object’s NetworkFixedUpdate
, and hence take control of it, that client must be the Input Source of that object. Otherwise, FetchInput
will return false. To check if you are the Input Source, use IsInputSource.
The server can also be the Input Source of objects, although it won’t do any CSP, since it needs not to, after all, it’s the server.
You can set the Input Source of an object when instantiating it:
To set/remove the Input Source (must only be called on the server):
Call
PermitInput
to set the Input Source of the object:Object.PermitInput(client);
Call
RevokeInput
to remove the Input Source of the object:Object.RevokeInput();
There are several methods you can override to run code when Input Source is assigned/removed or has left:
OnInputPermitted
: called on the player who was given permission to provide inputs to this object.OnInputRevoked
: called on the player whose permission to provide inputs to this object has been revoked by the owner (server).OnInputSourceLeft
: called on the owner (server) when the Input Source client has left the game.
Last updated
Was this helpful?