Debugging Game P5js

It is a game where you avoid the incoming enemies.
Uncaught TypeError: Cannot read property ‘x’ of undefined (sketch: line 62)
whenever the enemy hits the player

//loop through all enemies
  for(var i = 0; i < enemies.length; i++)
  {
    enemies[i].display();
    
    if(dist(player.x, player.y, enemies[i].x, enemies[i].y) < 20)
    {
     	enemies.splice(i, 1);
      lives = lives - 1;
    }  
    if(enemies[i].x > width)
    {
      enemies.splice(i, 1);
      score++;
    } 
  }

function Player()
{
  
  this.x = width/2;
  this.y = height - 100;
  this.direction = "stopped";
  
  this.display = function()
  {
    // make it wrap
    if(this.y > height)
    {
			this.y = 0;
    }
    if(this.y < 0)
    {
      this.y = height;
    }
    
    // direction
    if(this.direction === "up")
    {
      this.y = this.y - 3
    }
    if(this.direction === "down")
    {
      this.y = this.y + 3
    }
    
    // what player looks like
    fill(0, 255, 0);
    rect(this.x, this.y, 20, 20);
  }
}

function Enemy()
  {
    this.x = 0;
    this.y = random(0, 300);
    this.speed = random(1, 5);
    
    this.display = function()
    {
     	this.x = this.x + this.speed
      
      fill(255, 0, 0);
      ellipse(this.x, this.y, 20, 20);
    }
  }

You’re removing an element from the array using the splice() function, but then you’re using the index you just removed in the very next if statement.

1 Like