Game Development Reference
In-Depth Information
The update and render functions calculate and move the sprite positions during the game loop. This
technique was used in Break-It, and it works the same here in Space Hero. The updating and rendering of the game
sprites will be closely looked at in the upcoming sections.
Building the Update Functions
The update functions calculate the current positions and states of all active sprites and determine where they should
be rendered next. All update functions will be examined in detail next.
Updating the Star Field
All stars in the game should move in a constant manner down the screen. This gives the illusion of the ships traveling
through space. Listing 11-21 shows the update function for the stars.
Listing 11-21. The udpateStars Method Moves All Stars Down the Screen
p.updateStars = function () {
var i, star, velY, speed, nextY;
var len = this.stars.length;
for (i = 0; i < len; i++) {
star = this.stars[i];
velY = star.speed * this.delta / 1000;
nextY = star.y + velY;
if (nextY > screen_height) {
nextY = -10
}
star.nextY = nextY;
}
}
The stars array is looped through to access each star in the game. The star's next position is calculated and
dynamically assigned to each star as nextY . If the star's next y position puts it below the height of the screen, it is
recycled by placing it above the stage. Since the star sprites are so minimal, the need to make a class specifically for
them was bypassed.
Updating the Hero and Enemy Ships
The ships in the game are updated similarly to the stars in that their nextY and/or nextX properties are updated for
the next render cycle. Both update functions are seen in Listing 11-22.
Listing 11-22. Updating the Hero and Enemy Ships
p.updateHeroShip = function () {
var velocity = this.heroShip.speed * this.delta / 1000;
var nextX = this.heroShip.x;
var nextY = this.heroShip.y;
if (this.leftKeyDown) {
nextX -= velocity;
if (nextX < this.leftWall) {
 
Search WWH ::




Custom Search