Determining a collision between the player and tiles
In this task, we will determine the collision between the player and obstacles tiles.
Prepare for lift off
We need an array to store the tile IDs (obstacles). Let's put the following code in the setting.js
file:
game.BLOCKS = [100];
Engage thrusters
Let's add collision detection with the following steps:
- Inside the constructor of the
Tile
definition, we store a Boolean value to determine whether this tile is an obstacle. Since most of the tiles aren't obstacles, we initialize this variable withfalse
:this.isBlock = false; for (var i = 0, len=game.BLOCKS.length; i < len; i++) { if (type === game.BLOCKS[i]) { this.isBlock = true; } };
- The following code inside the
moveDown
function of a tile, checks whether the tile collides with the player, when the tile itself is an obstacle:if (this.isBlock) { this.checkCollison(); }
- Next, we define the
checkCollision
function inside theTile
definition. It uses the position coordinates...