2 Know your Enemies



Send in the ghosts

Ghostly objects

In the last lecture we have already learned about arrays to store numbers. We used them to store our level design.

Wouldn`t it be great if we could store our in-game enemies – in our case the ghosts – also in an array? Then we could loop thorugh the ghost array and update all ghosts positions etc.

In order to make ghost storable in an array we need to define a "ghost object". This object holds all attributes of our ghosts:

  var ghost = {
    posX: 5,
    posY: 3,
    speedX: 1,
    speedY: 0  
  }
  

Then we can create an empty array and append our new ghost object to the array:

  var allGhosts = [];
  allGhosts.push(ghost);
  

Now we can easily iterate over all ghosts and update their positions. Of course in this first example, for now just one ghost lives in our array.

  
    allGhosts.forEach((g) => {
      g.posX += g.speedX;
      g.posY += g.speedY;
      ellipse(g.posX, g.posY, 30, 30);
    });
    


Ghost town
Can you fill the array with 4 ghost objects on different positions moving to different directions?




Detecting collisions

A Simple Way to Detect Collisions

As we know the coordinates of all ghosts and our avatar in the matrix of the 2D game world, we can simply compare them every frame. Just like we did with the avatar and the walls in the last chapter.
If the coordinates of at least one ghost are the same as our avatar, there must be a collision as they sit on the same square.

Inside the loop iterating over all ghost objects we can write:

    if (g.posX == xPos && g.posY == yPos){ // test if x/y coordinates of ghosts are the same as avatar
        noLoop();   // stop the game
    }
    

Here`s a version of our little Pac Man clone that detects the collisions with four ghosts.



Using external libraries to make our lifes easier

However, checking coordinates of objects in a matrix is not enough for every type of game. Sometimes more precision or flexibility is needed.

Collision detecton in JS

p5.play library
Examples

Upload and load the library in HTML:

 
      

Define Sprites:

 
        s = createSprite(300, 350, 50, 50);
    

Move Sprites:

      s.velocity.x = -10;
      s.velocity.y = 0;
    

Load images in sprites:

    let img = loadImage('spaceship.png');
    s.addImage(img);
    

Check collision of sprites.