views:

435

answers:

8

I understand why it does that but I don't really have any idea of how to prevent that. So the scenario is, every frame I move the car by a certain of predefined pixels. What happens is when I go on slow or faster computer... well I get less or more frames per seconds so the car moves either slower or faster. I was wondering how I could prevent that.

I suspect that I would have the same problem using any library... This is my first time doing real time stuff like that.

+10  A: 

Move car according to timers and not framerate. i.e. Car model should be independent of the display representation.

Artyom
Would the timer calculate the time between each frame if I understand correctly?
Apoc
@Apoc, yes. You will have a much more consistent game if you go based on time instead of framerate
Polaris878
A: 

You have to save the time before moving car and drawings.
Save the time after all calculations.
Move your car by Npixels/second

Mykola Golubyev
+2  A: 

The movement should be constrained by a "real" time delay, i.e. you car will move at the speed of x pixel per time slice.

Max
+2  A: 

Read the real-time clock, and move the car an appropriate distance for the elapsed time. This may look somewhat "jerky" if the computer is too slow, but makes the car speed independent of the CPU speed.

Jerry Coffin
+3  A: 

You can solve this by using precise timers and vector maths.

So, for the sake of argument lets suggest your drawing code could be called at any point in time, e.g. 1 second apart or 3 second apart or 0.02 seconds apart.

Take the car movement speed to be 40 pixels a second.

Hence, the number of pixels it should move is (TIME_NOW - LAST_FRAME_TIME) * 40px.

jamesj629
+1  A: 

You need to cap the framerate to X frames per second (60 FPS is the most common). This is a common feature in most multimedia frameworks, including SFML. For SFML I'd look into the Window/RenderWindow method SetFramerateLimit(unsigned int Limit).

Robert Vella
That doesn't fix the problem when frame rates go under 60.
Apoc
+9  A: 

I suspect your current code looks somehow like this

 // to be called every frame
 void OnEveryFrame()
 {
     MoveCar();
     DrawCarToScreen();
 }

But it should be like this:

 // to be called - for example - 50 times per second:
 void OnEveryTimerEvent()
 {
     MoveCar();
 }

 // to be called every frame
 void OnEveryFrame()
 {
     LockTimerEvents();
     DrawCarToScreen();
     UnlockAndProcessOutstandingTimerEvents();
 }

You have to set up an according timer event, of course.

Doc Brown
+1  A: 

You need to fix your timestep. Basically, every frame you move the car a distance that varies based on how much time has actually elapsed since the last update call. This way, you get the correct speed regardless of framerate.

munificent