See below my main game loop. I am looking for a way to limit this loop to 20 frames per second
private void renderFrame()
{
while (Running)
{
game_controls.CheckKeyPress();
Frame = game_graphics.DrawFrame();
Panel_Graphics.DrawImage(Frame, 0, 0,320, 320);
ThreadMonitor.MonitorFPS();
}
}
Below is the ThreadMonitor class:
class Monitor
{
private int FrameCount;
private long TickCount;
private int PanelPosition = 2;
private Font font = new Font(FontFamily.GenericSansSerif, 12);
private Graphics Monitor_Graphics;
public Monitor(Graphics g)
{
AllocConsole();
Monitor_Graphics = g;
}
public void MonitorFPS()
{
FrameCount++;
if (Environment.TickCount >= TickCount + 1000)
{
Console.WriteLine("Running: " + FrameCount + "fps");
FrameCount = 0;
TickCount = Environment.TickCount;
}
}
#region ShowConsole kernel32.dll
/// <summary>
/// Generates Console Window for debugging purposes
/// </summary>
/// <returns> Console </returns>
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
static extern bool AllocConsole();
#endregion
I want the frames to be generated evenly i do not want the game to stop for half a second.
i am unsure how to acheive this.
Waiting 50ms inside the loop will not make your game 20 FPS, it will make your game at most 20 FPS, generally slower, depending on the contents of your loop AND current system/CPU load. Just make sure you understand the difference.
A better way to do this would be waiting required number of milliseconds based on current Environment.TickCount in the beginning of the loop. For example, your TickCount is 120ms, and you expect next game tick at 150ms, you need to wait 30 milliseconds, if it's 160ms already, you don't need to wait at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With