- Home /
Inputs in fixed update ?
Here's my code :
void FixedUpdate(){
if (gm.inputs[player].down && !gm.prevInputs[player].down)
{
r.velocity = new Vector2(r.velocity.x, 0);
r.AddForce(new Vector2(0, 25), ForceMode2D.Impulse);
}
}
When Vsync is turned on (QualitySettings.vSyncCount = 1), everything works fine, when I press A on my controller the player jumps
But if I turn Vsync off (QualitySettings.vSyncCount = 0), Unity registers only 1/10 of the button presses and the physics become broken..
What can I do to fix that ?
Answer by Bunny83 · Mar 06, 2019 at 02:20 AM
Just move your jump code to Update. FixedUpdate only has a few uses which are all related to continuous forces. Any impulse forces can and should be applied in Update.
FixedUpdate can run several times per frame or not at all. If you have a high (visual) framerate, FixedUpdate will not run every frame. For example the default physics rate is 50 cps (calls per second). If your visual framerate is 400fps, FixedUpdate will only run every 8th frame (400/50 == 8). If a key down even happens in any of the other 7 frames it won't be recongnised inside FixedUpdate.
Likewise if the framerate is lower than the physics rate you will occasionally get two or more FixedUpdate calls per frame. That means key down event may be recognised several times since the key down state only changes between update calls. So if at the frame where a key down even happend FixedUpdate is called two times, you will see two key down events, even it's just one.
but when click "tap start" ball move befor and game over
How do you "start" your game? If you have a button or code that waits for the user to click, you should always wait and react to the release of the click, not the pressing down. Though the code snippet you posted is quite abstract since we don't know when and where "gm.inputs[player].down" is actually set, where you handle your previous input etc.
Though the general rule always applies: Do not read one time events in FixedUpdate.