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:

  1. 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 with false:
    this.isBlock = false;
    for (var i = 0, len=game.BLOCKS.length; i < len; i++) {
      if (type === game.BLOCKS[i]) {
        this.isBlock = true;
      }
    };
  2. 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();
    }
  3. Next, we define the 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();
        }
      }
    }

Objective complete

We have successfully made the game over scene when a player hits an obstacle.

Determining collision

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.

Determining collision
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.183.86