I’m creating a simple game using GDI+ in C#.
First of all I need a game loop, and a render loop. I’ve decided to break these in to two seperate threads. It seems to work, and runs extremely fast, but the reason I’m asking here is because I see people use timers for their game loops to make them run at a specific frame rate.
This obviously has the advantage, that you can be sure of the speed in which actors move. But my game loops just runs as fast as possible, like the Update function in Unity3D. Now to make sure that actors always move at the same speed, all I have to do is to multiply the move speed by the frame delta time (the time between each frame).
My render loop also runs as fast as possible. Is this a good game loop, why or why not?
// Constructor
public FormDisplay()
{
// Create a thread object, passing in the GameLoop method
var gameThread = new Thread(this.GameLoop);
// Start the game thread
gameThread.Start();
// Create a thread object, passing in the GameLoop method
var renderThread = new Thread(this.RenderLoop);
// Start the render thread
renderThread.Start();
}
private void GameLoop()
{
while (true)
{
// TODO: Insert Game Logic
}
}
private void RenderLoop()
{
while (true)
{
// TODO: Insert Render Logic
}
}
You should consider your screen refresh rate as your limiting factor. There is no point moving your actors 300 times a second if your screen only updates 100 times a second.
Likewise, rendering the screen 300 times a second when the monitor refresh rate is only 100 Hz may show tearing. This happens when you update the frame buffer while the buffer is being present to the screen, so the top half of your actor appears in the old place, the bottom part in the new place.
A good article about reducing flicker is Stack Overflow question Reduce flicker with GDI+ and C++.
Ideally, as a general game loop, your game thread should be processing and building a list to pass to the render thread for the next screen refresh (that is, you’re always processing for the next displayed frame). Both threads then wait for the next frame. This of course means you need to know when that happens – which I don’t think you can find out rendering using GDI+.