# How do I set an object's speed to arrive in X seconds?

I want to move an object to a point in the game world, I have the distance value which is far the player should move. I want to complete the movement in X seconds.

I have tried many equations and formulas to no success.

Speed = Distance/Time


This one doesn't seem to give me the right result. Thing is the game is updated 60 times a second and the movement is affected by delta time.

I'm pretty sure I am not taking the framerate in consideration.

What am I doing wrong?

Edit:

This is how I calculate the speed:

int dst = 500;
int time = 2; // in seconds
float speed = dst / time;


Doing it this way is making the movement instant and the game object is not traveling the distance in 2 seconds.

Every frame each game objects gets updated this way:

p.x += dir.x * speed * deltaTime;
p.y += dir.y * speed * deltaTime;


The dir vector holds the direction of movement which is calculated on mouse click:

Vector2 dir = new Vector2(mouseX, mouseY).subtract(objectX, objectY).normalize();


Delta time calculation:

long time = System.nanoTime();
float deltaTime = (time - lastTime) / 1000000000.0f;
lastTime = time;


Please note: The game object stops upon arrival.

• This question sounds very similar. Is it what you mean?
– Anko
Oct 12, 2015 at 21:52
• When you multiply your speed by elapsed time each update (ignoring fps), what behavior do you see? The approach you describe seems correct. Oct 12, 2015 at 21:55
• @Anko I think so, I am trying to calculate in what speed the object will move so it will travel the distance in X seconds. Oct 12, 2015 at 21:58
• @StevenHansen I have made an edit. Maybe you can help me now? Oct 12, 2015 at 22:05
• Is deltaTime a variable time step? (I mean, possibly a different value frame-to-frame?) Arguments against variable time steps for physics here.
– Anko
Oct 12, 2015 at 22:08

You are specifying a time in seconds as an integer value, but you are not taking into account the game's frames per second.

If your game was running at 1 frame per second, it would work, because after two frames (thus, two seconds), your object would have travelled the specified distance.

int dst = 500;

If your game is running at 60 FPS, the speed of the object would be 500 / 120, or 4.16.
float deltaTime = Gdx.graphics.getDeltaTime();