Moving object with preset timelapse

I am a newbie game developer.

I have one problem. Consider the following case.

I have a simple game with only one object - a ball. A ball can move only up and down from one side to another.

A User is allowed to set the game time and ball iteration count. An iteration is when the ball goes up to the topmost point and goes back to the bottommost point.

It should complete all iterations for the time user has set.

Here is an example.

Consider that a user has set the game time to 60 seconds, and the ball iterations option to 30.

We can find how much time do we have for an iteration 60/30 = 2 seconds. So the ball should complete the iteration for two seconds.

Let's assume we have a known frame rate and it is 30ms (update and drawing). So a single loop iteration takes 2000ms.

Next find iterations per a complete ball movement 2000/30 = 66 iterations. Also let's imagine that a distance from one side to another is 2000px.

So the ball need to complete 4000px per iteration.

Finally we can find out our movement delta 4000px/66 = 60 px . So ball will move 60px per a loop iteration.

But what to do if I don't frame rate, but what is more interesting what to do when the framerate is not static and we need to correlate it every time.

Please suggest an algorithm or an approach to solve this problem.

It seems that there should be a function, that will calculate position of a ball by the time passed from the game start, like sin (because ball is bouncing)

Thanks.

This is usually called a "time step"

One simple way to handle this is to track the total [game] time elapsed since the start of the game. Then you can find how much time the current frame needs to account for with a simple subtraction:

currentTime = GetTimeSinceStartup();
realDeltaTime = currentTime - lastFrameTime;
lastFrameTime = currentTime;


This "delta time" (often abbreviated dt or dT) represents the time that's passed since the previous frame - often in units of seconds for convenience.

(Note that subtracting two floating point numbers very similar in value can cause "catastrophic cancellation" leading to precision loss, so consider using an integer or double-precision type for your time since startup. Your deltaTime can safely use single-precision)

You can also combine your delta time with a multiplier between zero and one, to make the game run in slow-mo, or pause updates when a menu is displayed.

gameDeltaTime = realDeltaTime * gameSecondsPerRealSecond;


myPosition += myMovementSpeedPerSecond * gameDeltaTime;

phase += gameDeltaTime * cyclesPerSecond * 2f * PI;