I've been playing with silverlight as a gaming platform for a few months now. I've not published or released anything I've done yet, but I expect I will at some point. I am not much of a game developer really, and I've been hacking things together as best I can. I, like many other developers, have always found game development to be quite interesting. So for now I'll talk about how to create a game loop.
What are Game Loops Used For?
In most games you need to have some control over the passing of time. You always need to be constantly able to respond to user input without stopping the game waiting for this user interaction. It allows you an opportunity to have the game move with or without the player. This loop will allow you to have computer-controlled enemies and neutrals decide how to act and to take these actions.
How to Create a Game Loop
I've found two ways I like for creating game loops. I am sure that there are plenty of others. If you wanted to, you could also wrap these up into classes so it abstracts the ugly details of creating a game loop. Perhaps a class which just lets you create a new instance of the game loop class and lets you assign a method for handling the looping.
Since I am just trying to show the simple how to of it, I'll leave out the class and leave that as an exercise for the reader. The two ways I know of for creating game loops are to use a System.Windows.Threading.DispatchTimer or a System.Windows.Media.Animation.Storyboard. I prefer the timer simply because it feels more hacky to use a storyboard. This just feels more like it should be some sort of a timer managing this, so it's what I like to use.
// Initialize the Main Game Loop
_timer = new DispatcherTimer();
_timer.Interval = new TimeSpan(100);
_timer.Tick += new EventHandler(MainGameLoop);
_timer.Start();
What we've done here is just created this DispatchTimer and told it to run fire the MainGameLoop method every time the timer ticks. The timer has an interval set to 10 miliseconds in this example, so our loop should execute 100 times every second.
private void MainGameLoop(object sender, EventArgs e)
{
// ....
// Do Stuff Here For the Game
// ....
}
Again another exercise for the reader is to create a game by filling in that MainGameLoop as well as other portions of the code. I plan on fleshing out some games if I ever get enough free time to work on it. I'll be back to post some more stuff. I expect it will be more complicated that this. I just don't want to post my whole game yet. It will be released eventually. I am not making Duke Nukem Forever, so you can expect my game will actually release at some point.
Comments