HTML and CSS Reference
In-Depth Information
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:
context . translate ( x + . 5 * width , y + . 5 * height );
NOTE
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. Todothis, we will subtract half the width from each x attribute in ourpath draw
sequence, and we will subtract half the height from each y attribute:
context . moveTo ( 10 - . 5 * width , 0 - . 5 * height );
context . lineTo ( 19 - . 5 * width , 19 - . 5 * height );
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 calcu-
lated version of the code.
Example 8-6. Rotating an image from its center point
//canvasApp level variables
var
var rotation = 0 ;
var
var x = 50 ;
var
var y = 50 ;
var
var width = 20 ;
var
var height = 20 ;
Search WWH ::




Custom Search