Vishnu
Vishnu

Reputation: 2452

Make the character jump Based on Fps and Time

i am trying to make a character based on Time and FPS.

What i need is make my character jump last for exactly 1 second.Right now i am using below code and it makes the character jump for 1 second.But problem is ..if the fps is 60 character moves 60 pixels , and if fps is 30 it moves only 30 pixels...How can i solve this..

I need character to move 60 pixels regardless fps and within 1 second.

//Below is the requestanimation frame loop
// which runs the loop 60 to 30 times per second , 
//  which vary according to browser.

    function jumpcheck()
    {
    if(isjump)
    {
    ball.posy -=1; //make the character move 10 px based on fps..


    window.timeoutHandle = window.setTimeout(function() {
    isjump = false;
    }, 1000);
    }





    }
    }

note:request animation frame fps is something between 20 to 60 always changing.

Code as said by constantinous

var lastUpdate = Date.now();
function jumpcheck()
{
if(isjump)
{
speed = 1;
position = ball.posy;
var now = Date.now();
var dt = (now - lastUpdate) / 1000;
lastUpdate = now;
ball.posy = position + (speed * dt)

}
}

Upvotes: 0

Views: 66

Answers (1)

Constantinius
Constantinius

Reputation: 35059

For games it is usual to include the time since the last frame into your calculations. This time is usually called dt for delta-time. To calculate your new position you simply multiply the passed time with the current speed to get the new position. In pseudo-code this looks like this:

speed = ...
position = ...
dt = ...

position = position + (speed * dt)

Upvotes: 1

Related Questions