Game Development Reference
In-Depth Information
By subtracting the origin from the position, the sprite is drawn at an offset such that the position
somePosition indicates the center of the sprite. Instead of calculating the position relative to the
origin yourself, the drawImage method from the canvas context also has a way to specify the origin
offset. Here is an example:
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();
In this example, the first step is to save the current drawing state. Then, you apply transformations.
You start by translating to a given position. Then you call the drawImage method, in which you have
to provide a number of different parameters: which sprite will be drawn and (using four parameters)
which part of the sprite should be drawn. You can do this by indicating the sprite's top-left coordinate
and the size of the rectangle part that should be drawn. In this simple case, you want to draw the
entire sprite, so the top-left coordinate is the point (0, 0). You draw a rectangle part that has the same
width and height as the entire sprite. This also shows that it's possible to use this feature to store
multiple sprites in a single image file while having to load that file into memory only once. Later in this
book, in Chapter 18, you see a nice way to do this and incorporate it into your game applications.
Next you can indicate a position offset. You can see in the previous code that you set this offset to
the negative origin values. In other words, you subtract the origin from the current position. That way,
the top-left coordinate is moved to the origin. Say you have a ball sprite with a width and height of 22
pixels. Suppose you want to draw this ball at position (0, 0), which is the top-left corner of the screen.
Depending on the origin you choose, the result is different. Figure 5-4 shows two examples of drawing
a ball sprite at position (0, 0) with two different origins. The left example has the origin of the ball in the
top-left corner, and the right example shows the ball with the origin at the center of the sprite.
Figure 5-4. Drawing a ball sprite at position (0, 0) with the origin at the top-left corner of the sprite (left) or the center of the
sprite (right)
As you've probably noticed, subtracting one position from another is a bit cumbersome in JavaScript:
var pos = { x : somePosition.x - origin.x,
y : somePosition.y - origin.y };
Search WWH ::




Custom Search