Jump to content

  • Log In with Google      Sign In   
  • Create Account


#ActualSimonForsman

Posted 17 May 2013 - 01:01 AM

I'm not sure why nobody mentioned the right way to handle delta time.

Try this. It should independent of FPS, and computer's speed.

 

 


long startTime = System.nanoTime();
...
public void update(long milliseconds) {

// calculate delta time
long time = System.nanoTime();
float deltaTime = (time - startTime)/1000000000.f;
startTime = time;

// Handle all of the ship logic
 
// Update player position base on velocity

 
position = position.add(velocity.multiply(deltaTime));
 

 
// movement code
 
if(direction.equals("left"))
{
position.setX(position.getX() - speed*deltaTime ); // for example if speed = 100, then it will move 100 pixels per second.
}
else if(direction.equals("right"))
{
 
position.setX(position.getX() + speed*deltaTime );
}
}

 

That method isn't necessarily the "right" way as it actually makes the speed of the system affect the result of the simulation rather than the speed at which the simulation runs. The Fix your timestep link posted by Matias describes a more robust way to handle updates and is worth reading. (variable timesteps work great for some games but once you start mixing in more advanced physics it can give you some rather "interesting" results)


#1SimonForsman

Posted 17 May 2013 - 12:59 AM

I'm not sure why nobody mentioned the right way to handle delta time.

Try this. It should independent of FPS, and computer's speed.

 

 


long startTime = System.nanoTime();
...
public void update(long milliseconds) {

// calculate delta time
long time = System.nanoTime();
float deltaTime = (time - startTime)/1000000000.f;
startTime = time;

// Handle all of the ship logic
 
// Update player position base on velocity

 
position = position.add(velocity.multiply(deltaTime));
 

 
// movement code
 
if(direction.equals("left"))
{
position.setX(position.getX() - speed*deltaTime ); // for example if speed = 100, then it will move 100 pixels per second.
}
else if(direction.equals("right"))
{
 
position.setX(position.getX() + speed*deltaTime );
}
}

 

That method isn't necessarily the "right" way as it actually makes the speed of the system affect the result of the simulation rather than the speed at which the simulation runs. The Fix your timestep link posted by Matias describes a more robust way to handle updates and is worth reading.


PARTNERS