In this task, we will determine the collision between the player and obstacles tiles.
We need an array to store the tile IDs (obstacles). Let's put the following code in the setting.js
file:
game.BLOCKS = [100];
Let's add collision detection with the following steps:
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 with false
:this.isBlock = false; for (var i = 0, len=game.BLOCKS.length; i < len; i++) { if (type === game.BLOCKS[i]) { this.isBlock = true; } };
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(); }
checkCollision
function inside the Tile
definition. It uses the position coordinates to determine collision:Tile.prototype.checkCollison = function() { if (this.y === 400) { if ( (this.x === game.TILE_WIDTH && game.player.currentLane === 1) || (this.x === (game.TILE_WIDTH*2) && game.player.currentLane === 2)) { game.isGameOver = true; game.flow.gameOver(); } } }
We have successfully made the game over scene when a player hits an obstacle.
There are different approaches that we can use to determine a collision between two game objects.
In this running game example, we use a very basic one that uses only the position in the coordinate system to determine a collision.
The following figure shows the coordinates of the game. The player's y position is always at 400 pixels. When the player is in the first lane, he/she has 100 pixels as the x position, which is the tile's width. When the player is in the second lane, he/she has 200 pixels as the x position. When the obstacle tile has the same coordinates as the player, they collide.
3.15.183.86