Game Development Reference
In-Depth Information
It would be much nicer if you could write something like this:
var pos = somePosition - origin;
Unfortunately, this isn't possible in JavaScript. Some programming languages (such as Java and C#)
support operator overloading. This allows a programmer to define what should happen when, for
example, two objects are “added” to each other using the plus operator. However, all is not lost. It's
possible to define methods that perform these arithmetic operations on object literals such as the
one defined above. Chapter 8 deals with this in more detail.
Now that you know how to draw a sprite at a different origin, you can, for example, draw a balloon
such that its bottom center is attached to the mouse pointer. To see this in action, look at the
Balloon2 program. You declare an additional member variable in which you store the origin of the
balloon sprite:
var Game = {
canvas : undefined,
canvasContext : undefined,
backgroundSprite : undefined,
balloonSprite : undefined,
mousePosition : { x : 0, y : 0 },
balloonOrigin : { x : 0, y : 0 }
};
You can only calculate the origin once the sprite has been loaded. So, just to be sure, you calculate
the origin in the draw method by using the following instruction:
Game.balloonOrigin = { x : Game.balloonSprite.width / 2,
y : Game.balloonSprite.height };
The origin is set to half the width of the sprite, but to the full height. In other words, this origin is
the bottom center of the sprite, which is exactly what you want. Calculating the origin in the draw
method isn't ideal; it would be preferable if you could calculate the origin only once, just after the
image has been loaded. Later, you see a better way of doing this.
You can now extend the drawImage method in the Game object so that it supports drawing a sprite
at a different origin. The only thing you need to do for that is add an extra position parameter and
pass the x and y values in that parameter to the drawImage method of the canvas context. Here is the
complete method:
Game.drawImage = function (sprite, position, origin) {
Game.canvasContext.save();
Game.canvasContext.translate(position.x, position.y);
Game.canvasContext.drawImage(sprite, 0, 0, sprite.width, sprite.height,
-origin.x, -origin.y, sprite.width, sprite.height);
Game.canvasContext.restore();
};
Search WWH ::




Custom Search