Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

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.

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.

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).

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top