Trying to get all objects in array to have collision

For the past few days, I have been struggling to get all the objects in my arraylist to be able to collide with the player object, but I am just struggling to get it to work. Im just not sure how to reference the array in the collision detection itself.

This is the collision im using, and where the “spaceRock1.x, spaceRock1.y” is, Thats where im trying to referecne the arrayList of objects but im pretty sure i am doing it wrong.

  //collision between player and enemy
  for (int i = 0; i < spaceRock1.size() - 15; i++)
  {
    if (dist(player_1.x, player_1.y, spaceRock1.x, spaceRock1.y) < enemyRad + playerRad)
    {
      //if collision, game lost and set game state to "LOSE"
      lives--;
      if (lives <=0)
      {
        gameState = "LOSE";
      }
    }
  }

This is the arraylist i have created. I just followed the coding train arraylist tutorial and altered it from there


ArrayList<enemy> spaceRock1;

  spaceRock1 = new ArrayList<enemy>();

  for (int i = 0; i < 10; i++)
  {
    spaceRock1.add(new enemy());
  }

  for (enemy e : spaceRock1)
  {
    e.update();
  }

Any help would be greatful :slight_smile:
Many thanks

1 Like

Remarks

since the list contains many rocks you could name it spaceRocks as a plural (this is by convention).

  • It’s good that it starts with a lower-case letter since it’s an ArrayList. Lower-case is also Array, Variable name, object name (by convention).
  • By convention, class names start with upper case letter, so Enemy.

Your question

In the for loop (inside of it) you have to get the current space rock from the Arraylist first (because the list itself doesn’t have x,y, only its items have):

enemy currentRock = spaceRock1.get(i); // i is from the for-loop, so we loop over the Arraylist

Then:

if (dist(player_1.x, player_1.y, currentRock.x, currentRock.y) < enemyRad + playerRad)
    {

see https://www.processing.org/reference/ArrayList.html

Remark II

Why -15 in the for-loop…?

By the way

These lines of yours also get a rock “e” from the ArrayList and loop over the entire list:

for (enemy e : spaceRock1)
  {
    e.update();
  }

Warm regards, Chrisir

3 Likes

Thanks man, big help from you :slight_smile:

1 Like