HTML and CSS Reference
In-Depth Information
Now that you have worked out a method to scroll around the map by offsetting things in the X-axis and Y-axis,
let's see how you can adapt that to your current code. If you go back to the last code that you used in your update loop,
you'll notice that the starting row and column is hard-coded to 0, meaning that it will ignore the value of the offset.
As a reference, here's what you were doing before:
// Paint the "background"
var i = 0,
j = 0,
lastRow = (canvas.height / cellHeight) >> 0, // Grab the last row
lastCol = (canvas.width / cellWidth) >> 0; // Grab the last column
“Fixing” the lastRow and lastCol values is easy enough, all you need to do add the values of scrollX and scrollY
in the following way:
lastRow = ((canvas.height + scrollY) / cellHeight) >> 0, // Grab the last row
lastCol = ((canvas.width + scrollX) / cellWidth) >> 0; // Grab the last column
But what about the starting values for i and j ? In that case, you can divide the value of scrollX and scrollY by
cellWidth and cellHeight , like this:
i = (scrollY / cellHeight) >> 0,
j = (scrollX / cellWidth) >> 0;
However, you also need to keep in mind that as you modify the offset, you might have to show cells that weren't
showing up before, which means that you'll need to mark them as “modified” so that in the next loop they get
redrawn, as shown in Listing 8-23.
Listing 8-23. Marking Cells as Modified
// Listen for keypresses
window.addEventListener('keydown', function(e) {
switch (e.keyCode) {
case 37: // Left
case 65: // A
// Make sure that we can't scroll past our minimum value (0)
if (scrollX > 0) {
scrollX -= 10;
}
break;
case 39: // Right
case 68: // D
// Make sure that we can't scroll past our maximum value
// (Width of the Cell * Number of Columns)
if (scrollX < (cellWidth * gridCols)) {
scrollX += 10;
}
Search WWH ::




Custom Search