HTML and CSS Reference
In-Depth Information
Additionally, you need to keep in mind what happens when the circle is bigger than four cells. In Listing 8-10,
you increase the radius of the sphere from 10 pixels to 60, which means that it occupies a total area of nine cells.
In order to get the area of the bounding rectangle, you just need to calculate the top left corner and bottom
right corner.
function paintPlayer(ctx, x, y) {
var l = ((x - playerRadius) / cellWidth) >> 0, // Grab the left corner
r = ((x + playerRadius) / cellWidth) >> 0, // Grab the right corner
t = ((y - playerRadius) / cellHeight) >> 0, // Grab the top corner
b = ((y + playerRadius) / cellHeight) >> 0, // Grab the bottom ccorner
i = l,
j = t;
// Set the colour to a semi-transparent blue
ctx.fillStyle = 'rgba(0, 0, 255, 0.05)';
// Cycle between left-right and top-bottom, adding 1 for error correction
for ( ; i < r + 1 ; ++i ) {
for ( j = t ; j < b + 1 ; ++j ) {
// Paint the square
ctx.fillRect((i * cellWidth),
(j * cellHeight),
cellWidth,
cellHeight);
}
}
// Set the colour to a dark red
ctx.fillStyle = '#CC0000';
// Draw the circle
ctx.beginPath();
ctx.arc(x, y, playerRadius, 0, 2 * Math.PI);
ctx.fill();
}
Now that you can reliably detect which cells the circle's movements are affecting, you can proceed with the full
implementation of the dirty rectangles algorithm.
In Listing 8-10, you implemented a routine within the update loop that checked whether the cells had to be
repainted or not. So, instead of painting a square, all you need to do now is to set those cells as “modified.” The flag
check on the loop will take care of the rest. Listing 8-11 shows the relevant part to modify.

Search WWH ::

Custom Search