- Home /
GetKeyDown Space doesn't work correctly with FixedUpdate
I have private string _SPACEKEY = "spacekey"
and string _buttonPressed
. In Update() I catch user input like this
if (Input.GetKeyDown(KeyCode.Space))
{
_buttonPressed = _SPACEKEY;
}
And in FixedUpdate() I try to make player jump like this
if (_buttonPressed == _SPACEKEY)
{
_playerRigidBody.AddForce(new Vector2(_playerRigidBody.velocity.x, _playerSpeed * 1.5f), ForceMode2D.Impulse);
}
else //need this to stop player movement when A or D not pressed
{
_playerRigidBody.velocity = new Vector2(0, _playerRigidBody.velocity.y);
}
But that doesn't work the way it supposed to. Player doesn't jump each time I press Space. I tried to Log "if" statement in FixedUpdate and it works about 1 time out of ten when I spam Space button. I tried to put bool in GetKeyDown (like jump = true
) but it didn't work neither. Works perfectly if I place Jump logic in Update() but I don't want to do that. What's the way to solve this?
Answer by Bunny83 · May 02, 2020 at 11:49 PM
As @Cassos already said any XXXDown or XXXUp method from the Input class does not work reliable in FixedUpdate. The input is evaluated at the beginning of a frame. A "Down" or "Up" event is only true for a single frame. Since FixedUpdate does not necessarily run every frame (if the visual framerate is higher than the fixed update rate) you will miss some frames. Likewise if your visual framerate is lower than the fixed update rate you may detect the event twice.
In general do any input event detection in Update. Just do
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
_playerRigidBody.AddForce(new Vector2(_playerRigidBody.velocity.x, _playerSpeed * 1.5f), ForceMode2D.Impulse);
}
}
Note that impulse forces do not have to be applied in FixedUpdate. Only continuous forces should be applied in FixedUpdate.
Um, I'm kind of having the same problem but is there an alternative way that I can use space key without skipping frame?
Answer by Cassos · May 02, 2020 at 11:22 PM
Input.GetKeyDown doesnt work in FixedUpdate() cause sometimes it skips the frame at which u pressed the key.
And try using:
_buttonPressed = Input.GetKeyDown(KeyCode.Space);
Your answer
![](https://koobas.hobune.stream/wayback/20220612233131im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Placing Input.GetkeyDown() inside FixedUpdate() slows down the rate I can fire at 1 Answer
Should player input be caught in Update, and then raycasting in FixedUpdate for shooting mechanics? 1 Answer
How often does the internal physics calculation get called? 1 Answer
Fixedupdate rate stays at 90 instead of 60 1 Answer
Jumping randomly doesn't work 2 Answers