# Calculate Velocity/Speed for scrolling image

HI

I am new to SDL.

I am scrolling image from Right to left.
Image width - 8100
image height - 1080
Screen Width - 1920
Screen Height - 1080

Speed of the scroll is 200

How can i calculate the velocity? i have following code in my program.

// Calculate the deltatime
NewTime = SDL_GetTicks();
DeltaTime = (NewTime - OldTime) / 1000.0;
OldTime = NewTime;

Does above code to help calculate the velocity?

Speed of the scroll is 200

200 what? pixels per second? That information is important.

You also don’t normally calculate velocity. Video games are integrators. You make up a velocity and then add it to position in some way every frame. The simplest way is as follows:

``````float x = 0.0f;
float velocity = -200.0f; // negative because right-to-left
while (running) {
// ...
x += velocity*deltaTime;
// ...
SDL_Rect r = { (int)x, (int)y (int)width, (int)height}; // for rendering with
// ...
}``````

In your code, the units of your deltaTime are in seconds, because SDL_GetTicks() returns milliseconds and you divided by 1000 and it became seconds. I recommend doing everything with `float` because deltaTime is almost always between 0 and 1 and it adds up.

If you think back to math class, the units of velocity is in pixels/second, and the units of deltaTime are seconds. (px/sec)*(sec) = px. Or, velocity*time = position.

That should hopefully work, but as an aside, having a variable deltaTime is usually more trouble than it’s worth. It’s better to keep your deltaTime fixed.

Furthermore, you need to internalize and understand basic physics to program video games. At the very least, understand position, velocity, and how they relate to each other. You can learn physics for free on KhanAcademy. If you want to do gravity or speeding up you’ll need to learn about acceleration too.

Hi

200 what? pixels per second? That information is important.
Velocity = 200.0f

from the above statement velocity is 200 pixels per seconds or what is the unit?

I need speed of the scroll in pixels per seconds.

Correct me if i am wrong anywhere.

Many Thanks

Example
Velocity = 200.f
Frames Per Second = 60;
DeltaTime = 1/60 = 0.01666666666

200.f * 0.01666666666 = 3.33333333333.

3.33333333333 pixels is what we move every frame.
We have 60 of these updates a second.
60 * 3.33333333333 = 200. After 1 Second you will have moved 200 pixels

Thanks Smiles.

I will let you know.

Thanks

Where can i get from FPS = 60

I don’t see anything in my source.

Shall i share the source code?

Thanks

FPS is up to you to implement. I was just showing how the calculation works if you were updating 60 times a second. You can plug in any value for fps.