What I'd like to say is that I am a novice in game programming. I have experience in Actionscript, VB.NET, HTML, Javascript, and PHP.
I have just begun working with C# in my brand new project for school, a 2D RPG.
I have been using these two books for help:
- Visual C# Game Programming for Teens
- Visual Basic Game Programming for Teens
They are complete beginner books.
The game loop provided with the books are very strange. It does not make sense to me.
It feels like the frame rate is not constant because the game freezes every couple of seconds (not at specific intervals, just randomly pauses everything).
I don't know exactly how to explain it, but the game is unplayable like this.
I know for a fact that it has to do with the game loop. I ran it on two different computers.
My home computer was absolutely unplayable. The game frame rate went down to 3 FPS. My home computer has a Quad Core processor with 8GB of RAM.
My school computer is playable, but like I said, it freezes every couple of seconds. This PC is a dual core with only 2GB of RAM.
Here is some code that I have:
This function is true while gameOver is equal to false.
private void GameLoop()
{
frameRate = game.FrameRate();
ticks = Environment.TickCount;
lastTime = 0;
if (ticks > lastTime + 16)
{
lastTime = ticks;
#region CHECK GAMESTATE
//check which gameState is on and update accordingly
switch (game.gameState)
{
#region STATE_TITLE
case Game.GameStates.STATE_TITLE:
game.titleScreen.Draw();
break;
#endregion
#region STATE_PLAY
case Game.GameStates.STATE_PLAY:
game.playScreen.Draw();
break;
#endregion
#region STATE_OPTIONS
case Game.GameStates.STATE_OPTIONS:
switch (game.optState)
{
case Game.OptionStates.STATE_CONTROLS:
game.optScreen.DrawControls();
break;
case Game.OptionStates.STATE_HELP:
game.optScreen.DrawHelp();
break;
case Game.OptionStates.STATE_SETTINGS:
game.optScreen.DrawSettings();
break;
}
break;
#endregion
#region STATE_CHARACTER
case Game.GameStates.STATE_CHARACTER:
game.charBuilder.Draw();
break;
#endregion
#region STATE_LOAD
case Game.GameStates.STATE_LOAD:
game.loadScreen.Draw();
break;
#endregion
#region STATE_PLAYING
case Game.GameStates.STATE_PLAYING:
//game.gameDevice.Clear(Color.Black); MIGHT CAUSE LAG??
doScrolling();
doHero();
doSide();
//print info
game.Print(50, 10, "Player Position " + game.hero.Position.ToString());
game.Print(50, 90, "Scroll Position " + game.world.ScrollPos.ToString());
break;
#endregion
}
#endregion
//refresh window
game.Print(50, 50, "Frame rate: " + frameRate.ToString());
game.Update();
Application.DoEvents();
}
else
{
System.Threading.Thread.Sleep(1);
}
}
and
public int FrameRate()
{
//calculate core frame rate
int ticks = Environment.TickCount;
count += 1;
frames = count;
if (ticks > lastTime + 1000)
{
lastTime = ticks;
frames = count;
count = 0;
}
return frames;
}
I would really appreciate some help in making this game loop as good as possible.
Thank you for all your time.