Game Development Reference
In-Depth Information
Creating the Game Loop
The game is now initialized. It is time now for the action. Remember that the state machine will fire a run method on
the current scene with every tick, if it has one to call. This game does have a run method, and it is used to create the
game loop in the game. The run method is shown in Listing 11-19.
Listing 11-19. The run Function Runs the Game Loop
p.run = function (tickEvent) {
this.delta = tickEvent.delta;
if (!this.betweenLevels) {
this.update();
this.render();
this.checkForEnemySpawn(tickEvent.time);
this.checkForEnemyFire(tickEvent.time);
this.checkHeroBullets();
if (!this.heroShip.invincible) {
this.checkEnemyBullets();
this.checkShips();
}
this.checkHealth();
this.checkHero();
}
}
The run method does quite a few things. Remember that the state machine passes the tick event into the game
scene's run method. This is done because there are a few properties on the tick event that will help you in the game.
The first property used is the delta property, which is assigned to the game property delta . This property is used
to determine the next position for each moving sprite when updating. This technique is referred to as time-based
animation , as opposed to frame-based animation, which has been used in all previous game loop exercises. The delta
property tells you the difference in time since the last tick and can be used to determine how far the sprite should move,
based on a predetermined speed value. This allows you to get smoother, more consistent sprite animations over varying
framerates due to inconsistent processor speeds. This technique will be used when updating all sprites in this game.
After storing away the current delta value, a quick check is run to determine if the game is between levels. If
the game is not currently between levels (i.e. the hero is not currently exploding), a series of game loop functions
are called. Each of these functions will run the game and check for scenarios that call for further action. The first two
functions are the update and render functions, which are seen in Listing 11-20.
Listing 11-20. The update and render Functions
p.update = function () {
this.updateStars();
this.updateHeroShip()
this.updateEnemies();
this.updateHeroBullets();
this.updateEnemyBullets();
}
p.render = function () {
this.renderStars();
this.renderHeroShip();
this.renderEnemies();
this.renderHeroBullets();
this.renderEnemyBullets();
}
 
Search WWH ::




Custom Search