How do I add collision between player projectile and enemies?

Hi @Marfmamow,

At each frame, for every object that can collide you need to check if it collides with any of all other objects (except itself).

This depends on what you want:

  • Do projectiles collide with other projectiles? Same for enemies?
  • Do projectiles kill enemies?
  • Do you have multiple players?
  • Is your player hitbox the whole tile or the size of the sprite?

Also you might want to use Java’s object oriented features, specially abstract classes. Abstract classes define a “template” for classes that you need to implement later.

For example you might have a Collidable abstract class that is defined like so:

abstract class Collidable {
  int x, y, w, h;

  Collidable(int x, int y, int w, int h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
  }

  boolean isCollidingWith(Collidable other) {
    // Rectangle / Rectangle collision
    return x + w > other.x 
      && y + h > other.y 
      && x < other.x + other.w
      && y < other.y + other.h;
  }
}

class Player extends Collidable {
  Player(int x, int y, int w, int h) {
    super(x, y, w, h);
  }
}

class Enemy extends Collidable {
  Enemy(int x, int y, int w, int h) {
    super(x, y, w, h);
  }
}

Each collidable object has coordinates and size (assuming they are all rectangular shaped) and has a default implementation of rectangle collision. Then you can define a Player and Enemy class extending the collidable class so that they get the collision behavior without re-implementing it.

You can then test for collision with every object that is Collidable (thanks to polymorphism):

Player player = new Player(0, 0, 50, 50);
Enemy enemy = new Enemy(30, 30, 20, 20);

println(player.isCollidingWith(enemy));

// => true

Bonus: here is an example on how you can implement collision for objects with different shapes

Linked to your previous post:

3 Likes