I’m having trouble creating a solid game engine for my OpenGL application. It’s a game which consists of several sprites with a lot of action.
I created objects which are basically all of my sprites. Another object called ‘gameEngine’ loops through a set of calculations every something of a second (a timer), resulting in new game variables. After that, the sprite objects now know their drawing data.
The problem is, that after collecting all of my drawing data, the drawing should take place at exactly the right moment in time, resulting in a steady animation. Depending on the complexity of the current scene, the game calculations take an undetermined amount of time. So, the actual drawing takes place at different moments in time. How would I prevent that from happening?
To clarify, my approach goes something like:
// Every something of a second I call tick -(void)tick { drawingData = gameEngine(); draw(drawingData); }
There must be a best practice for building game engines like this I’m not aware of?
The best solution would be a multi threaded application – one thread calculating the drawing data into a buffer and one rendering the data.
If you are looking for a realy simple solution, just invert the order of calculation and rendering.
You calculate the first drawing data on application start up and when the timer fires you just draw it. After that you have all the time up to the next timer event to calculate the drawing data again.
But in general it may be a better solution to render at a variable frame rate – you avoid the problems if the machine is to slow for your desired frame rate and you provide high frame rates on fast machines.
You render frames as fast as possible – not with a fixed interval between each frame but instead with the real time the application is running. That means do not advance your objects by 20 milliseconds every frame, just move them to the position the current running time says.