0

I'm making a simple game in java, and I have many methods which test if two object collide. Objects include a man, enemy, arrow, wall, coin and so on. I have a bunch of methods which count for every type of collision which could occur, they look like this:

    public boolean collide(Arrow a, Enemy b)
    {
        Rectangle a1 = a.getBounds();
        Rectangle b1 = b.getBounds();
        if(a1.intersects(b1)) return true;
        else return false;
    }

Is there away to create a generic method? I tried using object a and object b as the arguments but the compiler compained it couldn't find getBounds() for the objects.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Joe
  • 173
  • 3
  • 10
  • 1
    Use a common interface of those classes instead of `Object`. That interface must contain a method `Rectangle getBounds();` and those classes must implement it. Also, you can replace the last two lines with `return a1.intersects(b1);` – jlordo Mar 09 '13 at 16:09
  • See [this answer](http://stackoverflow.com/a/14575043/418556) for an example of collision detection using `Shape` instances. – Andrew Thompson Mar 09 '13 at 16:23

3 Answers3

3

You can do something like :

public boolean collide(HasBounds a, HasBounds b){...

With the interface :

public interface HasBounds{
  Rectangle getBounds();
}

That you should define on your objects Arrow,Enemy etc... (you may already have an object hierarchy suitable for that).

benzonico
  • 10,635
  • 5
  • 42
  • 50
1

what do you think of this..

 public boolean collide(Rectangle a1, Rectangle b1)
 {
        return a1.intersects(b1);
 }

or may be Create an interface

public interface CanCollide {
   Rectangle getBounds();
}

and use it in the method...

 public boolean collide(CanCollide a, CanCollide b)
 {
     Rectangle a1 = a.getBounds();
     Rectangle b1 = b.getBounds();
     if(a1.intersects(b1)) return true;
     else return false;
 }

Hope you find it usefull.

Thanks!

@leo.

lemil77
  • 341
  • 1
  • 8
-1

Just make abstract class GameObject with method: Rectangle2D getShape(). This method could look like:

abstract class GameObject {
    private Image image;

    GameObject(String path) {
        try {
          image = ImageIO.read(new File(path));
        } catch (IOException ex) {}
    }

    Rectangle2D getShape() {
       return new Rectangle2D.Float(0, 0, (int)image.getWidth(), (int)image.getHeight());
    }
}

Player, Enemy, Arrow, Wall would be subclasses of GameObject class

Michał Tabor
  • 2,441
  • 5
  • 23
  • 30
  • And how does this reduce the number of `collide()` methods? – jlordo Mar 09 '13 at 16:17
  • Now you don't need to overload collide() method with different collids modifications. Instead there is one method width parameters: (GameObject collid1, GameObject collid2) – Michał Tabor Mar 09 '13 at 16:19
  • That should be part of the answer. The constructor and `getShape()` methods have nothing to with OPs problem.. – jlordo Mar 09 '13 at 16:20