Fine Scrolling the Row and Column Buffers

The secret in fine scrolling the canvas is in the row and column buffers. These contain an extra tile (outside the viewable Camera area) that is not needed in coarse scrolling. The buffer is very important because when we fine scroll, we are usually painting only part of the tiles that are on the left, right, top, and bottom edges of the viewable camera.

If camera.x and camera.y are both at 0 (the top left edge of the tile map), we don’t need a scroll buffer. If camera.x or camera.y is at ANY other position on the game map screen, we need a scroll buffer for whichever (or both) dimensions are greater than 0, but not at the far right or bottom edge of the viewable world (as described earlier). As you can probably imagine, when playing a game, these x and y values will seldom be 0. Let’s take a close look at some examples of this now, because it is the crux of how we calculate and paint the game screen when fine scrolling.

Here is the code we will use to decide whether to use a row or column buffer when we draw our tile map when fine scrolling:

if (camera.x<=0) {
    camera.x=0;
    colBuffer=0;
}else if (camera.x > (world.width - camera.width)-scrollRate) {
    camera.x=world.width - camera.width;
    colBuffer=0;
}else{
   colBuffer=1;
}

if (camera.y<=0) {
    camera.y=0;
    rowBuffer=0;
}else if (camera.y > (world.height - camera.height)-scrollRate) {
    camera.y=world.height - camera.height;
    rowBuffer=0;
}else{
    rowBuffer=1;
}

The algorithm finds the necessary colBuffer ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.