Game Development Reference
In-Depth Information
Moving Sprites
Now that you're able to draw a sprite on the screen, you can use the game loop to make it move,
just like you did with the square in the MovingSquare example in Chapter 3. Let's make a small
extension of this program that changes the balloon's position based on the passed time. In order
to do that, you have to store the balloon position somewhere. You need to calculate this position in
the update method and draw the balloon at that position in the draw method. Therefore, you add a
variable to the Game object that represents the position, as follows:
var Game = {
canvas : undefined,
canvasContext : undefined,
balloonSprite : undefined,
balloonPosition : { x : 0, y : 50 }
};
As you can see, you define the position as an object consisting of two variables ( x and y ) in the Game
object. You can now add an instruction to the update method that modifies the x-position depending
on the time passed, just as you did in the MovingSquare example. Here is the update method:
Game.update = function () {
var d = new Date();
Game.balloonPosition.x = d.getTime() % Game.canvas.width;
};
Now the only thing left to do is make sure you use the balloonPosition variable when you draw the
balloon on the screen in the draw method:
Game.drawImage(Game.balloonSprite, Game.balloonPosition);
Loading and Drawing Multiple Sprites
Building games with only a plain white background is somewhat boring. You can make your game a bit
more visually appealing by displaying a background sprite. This means you have to load another sprite
in the start method and extend the draw method in order to draw it. The final version of this program
is called FlyingSprite, and you can find the complete source code in the sample folder belonging to
this chapter. If you open the program FlyingSprite in your browser, you see that now two sprites are
drawn: a background and, on top of it, a balloon. To achieve this, you add another variable to contain
the background sprite. Like the balloonSprite variable, this variable is part of the Game object:
var Game = {
canvas : undefined,
canvasContext : undefined,
backgroundSprite : undefined,
balloonSprite : undefined,
balloonPosition : { x : 0, y : 50 }
};
 
Search WWH ::




Custom Search