- Home /
Not registering input when checking input in Update and using input in FixedUpdate
Hi All,
Currently I'm trying to implement jumping but am running into loss of input.
I'm capturing input in the Update
method like so:
private void Update()
{
jumpInput = Input.GetKeyDown(KeyCode.Space);
}
Where jumpInput
is a bool member variable.
I'm attempting to use the jumpImput
variable in the FixedUpdate
method as follows:
private void FixedUpdate()
{
if (jumpInput)
{
rigidBody.velocity += new Vector3(0f, -rigidBody.velocity.y + jumpSpeed, 0f);
}
}
But something is going awry. The player does not always jump when the space bar is pressed. It seems that sometimes the input is missed.
What is the best way to use input captured from Update
in FixedUpdate
? How can I prevent the input loss I am experiencing?
Answer by Edy · May 03 at 07:51 AM
Multiple Update calls typically happen between each FixedUpdate call. Space may be detected in an Update, but the consecutive Update resets the variable to false so it doesn't reach FixedUpdate.
Solution: use OR instead of direct assignment:
void OnEnable()
{
jumpInput = false;
}
void Update ()
{
jumpInput |= Input.GetKeyDown(KeyCode.Space);
}
void FixedUpdate ()
{
if (jumpInput)
{
/// ... do something
jumpInput = false;
}
}
Note the "|=" instead of "=" in Update. This is the logical OR assignment, equivalent to "jumpInput = jumpInput | Input.GetKeyDown(...)".
Your answer
Follow this Question
Related Questions
Is it okay to use ForceMode.VelocityChange in Update()? 1 Answer
Supplying Input from Update To FixedUpdate 1 Answer
Mouse Input for RayCast - Update or FixedUpdate 1 Answer
How do I pass an input in Update() to FixedUpdate() for Physics movement? 2 Answers
Input and applying physics, Update or FixedUpdate? 3 Answers