Book Image

HTML5 Game Development Hotshot

By : Seng Hin Mak, Makzan Makzan (Mak Seng Hin)
Book Image

HTML5 Game Development Hotshot

By: Seng Hin Mak, Makzan Makzan (Mak Seng Hin)

Overview of this book

Table of Contents (15 chapters)
HTML5 Game Development HOTSHOT
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...