Input in Void Update not working,Input not always registering in void update
I have an input in void update which starts an action in fixed update. the input doesn't always register. Please help.
void Update() { moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")).normalized; if (Input.GetButtonDown("Jump")) { jumpRequest = true; } else { jumpRequest = false; } } void FixedUpdate() { if (jumpRequest) { rb.AddRelativeForce(Vector3.up * jumpVelocity, ForceMode.Impulse); } }
,I have an input in void update that starts an event in fixed update. the input doesn't always register (as if the input was in fixed update). Can someone please help.` void Update() {
if (Input.GetButtonDown("Jump"))
{
jumpRequest = true;
}
else
{
jumpRequest = false;
}
}
void FixedUpdate()
{
if (jumpRequest)
{
rb.AddRelativeForce(Vector3.up * jumpVelocity, ForceMode.Impulse);
}
}`
Answer by Bunny83 · Dec 14, 2019 at 11:56 PM
Once more a case where people do not understand the point of FixedUpdate. You only need it for applying continuous forces over time. There is no problem applying an impulse force in Update
So you can simply do this in Update:
if (Input.GetButtonDown("Jump"))
{
rb.AddRelativeForce(Vector3.up * jumpVelocity, ForceMode.Impulse);
}
FixedUpdate does not necessarily run every frame. Especially if your actual framerate is high. Let's just assume a visual framerate of 100 fps. In this case FixedUpdate would only run once every two visual frames. That means when you detect the button down even in Update and just set the boolean to true, it will only be true for that one frame since you set it back to false the next frame. If that happens on a frame where fixedupdate doesn't run at all it would completely miss that event. Your boolean would work if you do not reset the boolean in Update but actually inside FixedUpdate. This works but is unnecessarily complicated:
void Update()
{
if (Input.GetButtonDown("Jump"))
{
jumpRequest = true;
}
}
void FixedUpdate()
{
if (jumpRequest)
{
rb.AddRelativeForce(Vector3.up * jumpVelocity, ForceMode.Impulse);
jumpRequest = false;
}
}
This does work because the boolean stays true until at least one FixedUpdate has run and has "consumed" your event. If you have trouble understanding How FixedUpdate works, I made this animation years ago. If you want to understand it from a code point of view, you can look at my CustomFixedUpdate class which does the same thing that Unity does for the built in FixedUpdate callback. Since Unity has provided us with the Physics.Simulate method they even put an example in the docs how the FixedUpdate works