I implemented variable jumping in unity for an endless running game. My question, how can I make the jump frame rate independent?

My algorithm

if ( keyDown ){
isJumping = true
ySpeed += jumpStep*Time.deltaTime;
if( ySpeed > maxJumpHeight )
    ySpeed = maxJumpHeight;
// Apply gravity
ySpeed -= ( currentGravity * Time.deltaTime ) ;
// set position
playerSprite.transform.localPosition = new Vector3(0,currentPos.y+ySpeed,0);

This varies on different devices, What I am trying to do that, whatever the device is, the jump should always be the same on a given time.

What if i do this in FixedUpdate? Will it work fine?

  • You shouldn't multiply jumpStep by Time.deltaTime. It should always be the same value, regardless of frame rate.
  • You should multiply currentGravity by Time.deltatime.
  • In the last part, you should do currentPos.y + ySpeed * Time.deltaTime, When you use speed to compute movement, you need to multiply speed by time.

That is because jumping is an impulse and gravity a force. Impulses happen in an infinitely small time frame. Forces act over time.

| improve this answer | |
  • \$\begingroup\$ If the jumpStep is same on every frame,the jump will take more time to reach MAXIMUM on 30FPS and less on 60FPS. How can I make sure then it should always jump at max 100 in 2 seconds? \$\endgroup\$ – ahmedkl Apr 10 '14 at 12:41
  • \$\begingroup\$ You should have one piece of code that decides if the player is on the ground and hit the jump key. You cannot jump whilst in mid-air. Then, whenever the character can jump and the players hits the jump button, you should set ySpeed to the jump movement speed. After that, each frame, adjust the y-position and the speed and it should work fine. The jump should end when gravity takes the character back to the ground. It will always take initial_jump_speed / current_gravity time. So it should work fine even if you set the initial jump speed to a constant value. \$\endgroup\$ – AturSams Apr 10 '14 at 12:59
  • \$\begingroup\$ by "adjust the yPosition and speed" you mean that I should calculate the ySpeed based on the current delta time? \$\endgroup\$ – ahmedkl Apr 10 '14 at 18:03
  • \$\begingroup\$ Yes, that is correct. Just one thing.. It will take initial_jump_speed / current_gravity for the jump speed to reach zero and the character will stop gaining height and begins to fall. \$\endgroup\$ – AturSams Apr 11 '14 at 17:25
  • 1
    \$\begingroup\$ "Impulses happen in an infinitely small time frame. Forces act over time." best explanation I've read about this so far. \$\endgroup\$ – o0'. Apr 16 '14 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.