The Camera Object
The viewable window the user will see is called the Camera. It displays just a portion of the tile-based world at a single time. We allow the user to move the camera with the arrow keys to scroll through our tile-map.
The camera will have these attributes:
camera
.
height
=
theCanvas
.
height
;
camera
.
width
=
theCanvas
.
width
;
camera
.
rows
=
camera
.
height
/
world
.
tileHeight
;
camera
.
cols
=
camera
.
width
/
world
.
tileWidth
;
camera
.
dx
=
0
;
camera
.
dy
=
0
;
camera
.
x
=
0
;
camera
.
y
=
0
;
The camera object is not complicated. It contains just the
necessary attributes to move and paint it to the screen during a
setTimeOut
interval based on user key
presses. Its height
and width
come directly from the Canvas size
(160×160). The x and y values
represent the upper left corner of the camera of the game world. In
coarse scrolling, this is either 0
or
a multiple of 32
(our tile height and
width). The maximum value for the upper left corner of the camera on the
x-axis is the world width (480 in our example) minus the camera width
(160 in our example). This way, the camera never tries to paint tiles
that do not exist in our world map array.
Fine scrolling is similar, but the values for x
and y
top
left corner, or the camera, can each be 0
or any number up to a maximum we calculate to ensure that we are not trying to paint tiles that do not exist off the right side or bottom of the tile-map. In essence, we don’t need to scroll 32 pixels at a time but, rather, any number from 1 to 32 (or more, but that would result ...
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.