Game Status: Not Started

Collision Mechanics with an Enemy

Run the level above and move the player into the npc, and notice how the level restarts when you collide with the npc. This is done with the collision mechanics code from Enemy.js. Using this file’s logic, you can employ enemy collision mechanics in your own levels.

What are Collision Mechanics?

Collision mechanics can be broken down into two main parts:

  1. Detecting if two objects touch each other
  2. Act on that collision (take damage, die, stop, bounce, move etc)

Collision mechanics dictate when and what happens between two objects in a game.

Enemy.js

In our game engine, we can create enemies with consequential collision using the Enemy.js JavaScript class.

This class contains all the functions for the Enemy and can create consequences for player collisions. It extends the Character.js class.

Code:

import Character from './Character.js';
import Player from './Player.js';

class Enemy extends Character {
    constructor(data = null, gameEnv = null) {
        super(data, gameEnv);
        this.playerDestroyed = false; // Tracks if the player has been "killed"
    }

    // Overrides the update method to handle collision detection.
    update() {
        // Start by drawing the object
        this.draw();

        // Check if the enemy collides with the player
        if (!this.playerDestroyed && this.collisionChecks()) {
            this.handleCollisionEvent();
        }
    }

    // Checks if the Enemy collides with the Player.
    // Returns true if a collision is detected, otherwise false.
    collisionChecks() {
        for (const gameObj of this.gameEnv.gameObjects) {
            if (gameObj instanceof Player) {
                this.isCollision(gameObj);
                if (this.collisionData.hit) {
                    return true;
                }
            }
        }
        return false;
    }

    // Handles what happens when the player collides with the enemy.
    handleCollisionEvent() {
        console.log("Player collided with the Enemy. Player is dead.");
        this.playerDestroyed = true; // Mark the player as "dead"
        this.gameEnv.gameControl.currentLevel.continue = false; // Restart the level
    }
}

export default Enemy;
;

How the code works

The enemy class extends the class “character” and checks if the player has collided with an enemy.

If the enemy hits the player, the code returns true, and if it is true, it destroys the player and restarts the gameloop to make the player return to the home screen.