HTML and CSS Reference
In-Depth Information
Game Graphic Transformations
As we saw in the previous section, we can easily rotate a game graphic at the top-left
corner by using the context.rotate() transformation. However, our game will need to
rotate objects at the center rather than the top-left corner. To do this, we must change
the transformation point to the center of our game graphic object.
Rotating the Player Ship from the Center
The code to rotate the player ship from its center point is almost exactly like the code
used to rotate it at the top-left corner. What we need to modify is the point of the
translation. In Example 8-5 , we placed the immediate-mode drawing context at the x
and y coordinates of our game object ( 50 , 50 ). This had the effect of rotating the object
from the top-left corner. Now we must move the translation to the center of our object:
The width and height variables represent attributes of our drawn player
ship. We will create these attributes in Example 8-6 .
This is not the only change we need to make; we also need to draw our ship as though
it is the center point. To do this, we will subtract half the width from each x attribute
in our path draw sequence, and half the height from each y attribute:
As you can see, it might get a little confusing trying to draw coordinates in this manner.
It is also slightly more processor-intensive than using constants. In that case, we would
simply hardcode in the needed values. Remember, the width and height attributes of
our ship are both 20 . The hardcoded version would look something like this:
context.moveTo(0,−10); //10-10, 0-10
context.lineTo(9,9); //19-10, 19-10
The method where we use the calculated values (using the width and height variables)
is much more flexible, while the hardcoded method is much less processor-intensive.
Example 8-6 contains all the code to use either method. We have commented out the
calculated version of the code.
Example 8-6. Rotating an image from its center point
//canvasApp level variables
var rotation = 0;
var x = 50;
var y = 50;
Search WWH ::

Custom Search