- Home /
Eliminating input loss
I've been playing around with the prepackaged CharacterMotor script and have run into some confusion about how to best relate Update and FixedUpdate to one another.
All my input functions are placed tidily inside Update, then referenced in FixedUpdate, where their physical effects are executed. The problem I run into is that with any sort of instantaneous trigger, like GetKeyDown, sometimes FixedUpdate misses it and thus nothing happens.
An example of a script that would cause this:
Update(){
inputSuperJumpDown = Input.GetButtonDown ("SuperJump");
}
FixedUpdate(){
if (inputSuperJumpDown){
Debug.Log ("I'm super jumping!");
}
}
How is it that the prepackaged CharacterMotor manages to keep all its default jumping/physical behaviour contained within FixedUpdate (or functions called within FixedUpdate) seemingly without any loss of input?
Answer by Bunny83 · Mar 02, 2013 at 04:58 PM
The way you have your script at the moment would be the same as if you had read the input directly in FixedUpdate. Input changes only between Frames. So each Update the input changes. The problem with FixedUpdate is that it might not be called between two updates. Since you set / reset your variable every Update it just directly reflects the state you get from Input.GetKeyDown.
One way to handle one time events is this:
function Update()
{
if (Input.GetButtonDown ("SuperJump"))
inputSuperJumpDown = true;
}
function FixedUpdate()
{
if (inputSuperJumpDown)
{
inputSuperJumpDown = false;
Debug.Log ("I'm super jumping!");
}
}
So when the key is pressed the variable remembers the "down event". Once FixedUpdate is called it sees the state and resets it.
However for one time events you don't have to use FixedUpdate. It's only important if you apply physics over time and therefore over multiple frames. So just put your one-time-code in Update:
function Update()
{
if (Input.GetButtonDown ("SuperJump"))
{
Debug.Log ("I'm super jumping!");
}
}
That is incredibly helpful and clears up a lot for me. Thanks a bunch!
THAAAAAAAAAAAAAAAAAAAAAAAAAAANK YOUUUUUUUUUUUUU. This fixed my life