HTML and CSS Reference
In-Depth Information
},
draw: function(ctx) {
var p = this.p,
viewport = this.parent.viewport,
viewW = Q.width / viewport.scale,
viewH = Q.height / viewport.scale,
startBlockX = Math.floor((viewport.x - p.x) / p.blockW),
startBlockY = Math.floor((viewport.y - p.y) / p.blockH),
endBlockX = Math.floor((viewport.x + viewW - p.x) / p.blockW),
endBlockY = Math.floor((viewport.y + viewH - p.y) / p.blockH);
for(var y=startBlockY;y<=endBlockY;y++) {
for(var x=startBlockX;x<=endBlockX;x++) {
this.drawBlock(ctx,x,y);
}
}
}
The rendering code has been broken down into three separate methods. The
draw
method from the first
version is replaced with one that calculates the starting and ending block in each direction and then calls the
drawBlock
helper method for each block.
The
drawBlock
method takes in the block position and converts it into a pixel position to calculate the
startX
and
startY
variables. It then checks if an off-screen Canvas has already been created; if not, it calls
the
prerenderBlock
method to create it. The
drawBlock
method then draws the off-screen Canvas onto
the screen using the standard Canvas
drawImage
method, which accepts a Canvas element as a first parameter
(in addition to the standard image object).
Finally, the
prerenderBlock
method creates an off-screen Canvas sized to the dimensions of the block
and then draws each of the tiles in the block. It then saves the Canvas in the
this.blocks
property for later
reuse.
Handling Platformer Collisions
As mentioned earlier, collision detection in a platformer needs some special attention. The first issue, as de-
scribed already, is that, given the size of levels, collisions between sprites and tiles need to be highly optimized.
A second requirement is that the collision detection should be stable and reasonably accurate. Because sprites
spend most of their time hanging out on, well, platforms, the engine should be optimized for this case. Sprites
will also be running around jumping and generally causing a ruckus. As the sprites run into things, they need to
get feedback based on the direction of the impact.
Building a physics engine that does realistic collision calculations and responses to collisions is both difficult
and processor-intensive. A simpler solution is to build a simplified model of how a sprite should react to colli-
sions that is easier to implement and less work on the processor.
Taking a hint from the old-school platformers of yesteryear, sprites can be treated as a rigid collection of
points that represent the extents of the object. If each point is also given a position label like
top
,
left
,