HTML and CSS Reference
In-Depth Information
// Draw the circle
ctx.beginPath();
ctx.arc(x, y, playerRadius, 0, 2 * Math.PI);
ctx.fill();
}
}());
However, you will notice that whenever you move the dot, it leaves a trail. The reason why this happens is
because you're not “cleaning up after yourself ” by repainting the cells. In order to take care of this problem, first of all
you need to figure out where you are—that is, upon which cells the circle is sitting.
A naive solution to the problem would consist of cycling every cell asking, “Is the circle on top of me?” but that
would be an extremely time- and resourcing-consuming operation. Luckily, there's a much simpler solution that
consists in dividing the position in the X-axis by the width of the cell, and flooring the result. Keep in mind that you'll
need to do the same with Y-axis, by dividing it by the height of the cell.
You can try this concept by making a very small modification to the paintPlayer() function, as shown in Listing 8-9.
Listing 8-9. Modifying the paintPlayer() Function
function paintPlayer(ctx, x, y) {
var col = (x / cellWidth) >> 0,
row = (y / cellHeight) >> 0;
// Set the colour to a semi-transparent blue
ctx.fillStyle = 'rgba(0, 0, 255, 0.05)';
ctx.fillRect((col * cellWidth),
(row * 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();
}
But if you try this example in a web browser, you'll find situations like the ones in Figure 8-2 where even though
the circle is on top a cell, the cell is not being painted. The reason why this happens is because the X and Y are being
calculated from the center of the circle, and you're not taking the radius of the circle into account.
 
Search WWH ::




Custom Search