Unknown class through a function

void collision(Player player) {
  for (Wall wall : walls) {
     //find collision between player and wall, if they collide, stop player movement

Is it possible for the example above to have an unknown class passed through the function? For example i could pass through player or enemy and they both work in the same way.

1 Like

Create a shared parent class for those subclasses to inherit from. :bulb:

2 Likes

A very extensible method is using interfaces: All classes relevant to collision detection implement the Collidable but each class has to implement the methods themselves. Thus there are no inheritance problems. You can also check whether Enemies are colliding with other objects and so on:

ArrayList<Collidable> collidables = new ArrayList<Collidable>();
interface Collidable {
  float getX();
  float getY();
  // Etc. All you need for colliding
  void onCollide(); // Gets called on collision
}
class Player implements Collidable {
  // Implement interface methods and do other stuff
}
void collide(Collidable c) {
  for(Collidable collidable : collidables) {
    // If it collides run c.onCollide()! 
  } 
}

P. S. Writing this on a Smartphone. Syntax errors may or may not arise.

1 Like