Game Development Reference
In-Depth Information
The first special part is as follows:
context.translate(BRICK_SIZE / 2, BRICK_SIZE / 2);
context.rotate(this.rotation * Math.PI / 180);
context.translate(- BRICK_SIZE / 2, - BRICK_SIZE / 2);
What do we do here? We know that every brick saves its rotation in its this.rotation attribute. Before
we draw anything, we must rotate the drawing context to the correct angle. The rotation won't affect any
other bricks since the command happens between our context.save() and context.restore() pair. As
we said earlier, this will undo anything we did to the context, so we have a clean start before we draw the
next brick.
To be able to rotate the context correctly, we must translate it to the center of the rotation. The center is
actually the center of the brick, so we translate by the half of the brick size in both directions.
context.rotate() takes one argument, which tells it how far it should rotate the context in radians. Since
this.rotation is a degree value, we must convert it from degrees to radians. We do this by multiplying the
rotation with pi and dividing it by 180.
After finishing with the rotation, we translate by the negative half of a brick in both directions. This undoes
our translate command before the rotation. Since we took the rotation into account, we can now focus on
drawing the brick.
As with the circle, we start a new path and move to the coordinates (0, 0). Then we use the
context.bezierCurveTo() function to draw a quarter circle from the top-left corner to the bottom-right one.
From this corner, we draw a line to the bottom-left corner and are finished after closing the path. After
calling context.fill() , we are finished and can move on to the next brick, the triangle!
Triangle
With the triangle brick, it's the same as with the others. The first few lines are not really surprising.
var Triangle = function() {
this.row = 0;
this.column = 0;
this.type = "Triangle";
this.rotation = 0;
}
The triangle is also an asymmetric brick, so we need to take the rotation into account in the same way we
did with the curve brick. Nothing new here.
Triangle.prototype.draw = function(context) {
context.save();
context.translate(this.column * BRICK_SIZE, this.row * BRICK_SIZE);
context.translate(BRICK_SIZE / 2, BRICK_SIZE / 2);
context.rotate(this.rotation * Math.PI / 180);
context.translate(- BRICK_SIZE / 2, - BRICK_SIZE / 2);
 
Search WWH ::




Custom Search