Eko
Eko

Reputation: 1557

Speed in game with libgdx

I'm making a game using libgdx. For now, every character has a speed, corresponding actually to the number of render the game wait before update the character. For example, if the character has a speed of 15, it will be updated every 15 renders. I'm conscious that this is not how it has to be done.

What is the proper way to do this? I really want to make a speed in %, for example a character will have a speed of 85%.

Upvotes: 2

Views: 4780

Answers (2)

MilanG
MilanG

Reputation: 7124

When you calculate you object's next position just multiply it's speed with Gdx.graphics.getDeltaTime(), so the more time has pass since last render the more object will move. Movement speed will be constant, no matter of FPS.

However, simple solutions like this one always come with a catch! If you are i.e. moving a bullet it may happen that too much time has passed since last rendering (specially on mobile device). I.e. half of second, and for that time your bullet moved i.e. 100px and moved trough some target, but since it was never in range of detection (skipped it) target will be missed even it's not suppose to do so - player aimed well.

So, if just moving some object is not what you want, but you need that movement to be in some regular steps better way is not to multiply speed with delta time, but to repeat movement and all calculations (detections and stuff) depending on delta time. I.e.:

  • You have method move left(), which moves object one step and with that amount of movement everything works well.

  • Your method should be called 20 times per second (step takes 50mS).

  • You measured time since last render and it's 100mS, means that your objects need to be moved 2 steps

  • Don't just multiply it's speed and do one calculation - instead of that repeat whole calculation process 2 times! Call your left() method twice!

  • If time since last drawing is less then 50mS - then skip calculations and just draw graphics as you did in last frame.

This way you will have separated calculation rate from drawing rate. Calculation rate will be same on all devices, but drawing will depend on devices performance..

Upvotes: 2

desertkun
desertkun

Reputation: 1037

Use delta.

Gdx.graphics.getDeltaTime() method return secods since last render frame. Usually this value is very small, and it equal 1 / FPS.

@Override
public void render() 
{
    // limit it with 1/60 sec
    float dt = Math.min(Gdx.graphics.getDeltaTime(), 1 / 60f); 
    // then move your characted according to dt
    player.pos = player.pos + player.speed * dt;
    // or, you could mute the speed like this:
    player.pos = player.pos + player.speed * dt * 0.85;
}

Upvotes: 9

Related Questions