Putting actor logic in your game loop

It’s important to remember that we put things into objects for a reason.  One of the greatest reasons is to keep the logic in our code cleanly separated.  If you want the enemies to act one way, you change the code in the enemy object.  At a later point if you change your mind you simply pop some new logic into the object.

When you muddy the water by putting logic in the game loop it becomes harder and harder to work on your project.  It also makes it difficult for other team members to logically find your code.  Take a look at the example below:


update(time) {
foreach ( actor in game ) {
actor.update(time);
if(actor.type == "enemy") actor.x += 5;
if(actor.type == "player") Player(actor).score ++;
}
}

You’ll notice that for each “enemy” it will do an arbitrary movement of 5 pixels on the x axis.  What if you want to move it left 5 pixels instead?  Do you go to the actor object?  It gets harder and harder to find this logic.  The best game loops look like this:


update(time) {
foreach ( actor in game ) {
actor.update(time);
}
}

Later you’d see:


Enemy extends Actor {
update(time) {
x += 5;
}
}

Player extends Actor {
update(time) {
score ++;
}
}

Nice and tidy!

Not timing things based on elapsed time

You’ll notice something above, as well.  The update function is called on the game loop each frame and it’s passed the time elapsed.  When you do anything animation or time-based you have to take that timespan into account.  A player who gets one point every frame wont be very happy when his friends’ computer is playing at 100 frames per second and his at only 20.

Share:
  • Facebook
  • email
  • Twitter
  • MySpace
  • Google Bookmarks
  • Live
  • Digg
  • Technorati
  • LinkedIn