HTML and CSS Reference
In-Depth Information
4.
The next stage is to implement some form of collision detection to determine whether
or not the player is standing on the terrain or has collided with an obstacle. To do this
we will modify the
Update
function within the
Player
object. Insert the following
below the code that moves the player in a given direction:
var collision, position, curTile, terrainHeight, playerHeight;
if ((this.right || this.left) && !(this.left && this.right)) {
collision = false;
do {
position = this.left ? this.x : this.x + this.frameWidth;
curTile = this.level.CurrentTile(position);
terrainHeight = this.level.TerrainHeight(curTile);
playerHeight = context.canvas.height - (this.y + this.texture.
height);
if (playerHeight < terrainHeight) {
collision = true;
if (this.right)
this.x = this.level.tileWidth * curTile - this.frameWidth - 1;
else
this.x = this.level.tileWidth * (curTile + 1);
}
else
collision = false;
} while (collision)
}
5. The inal step is to implement the
Level
object. Create the
Level
object and insert
the following code in it:
function Level() {
this.tiles = new Array();
this.tileWidth = 0;
this.tileHeight = 0;
this.InitLevel = function() {
this.tileWidth = tile.width;
this.tileHeight = tile.height;
for(var i = 0; i < 50; i++) {
this.tiles[i] = 1;
}