Search code examples
javaswingcollision-detectionjava-2d

Implement collision detection by extendung the Rectangle class to use its contains and intersects methods


I would like to know if this is a good idea that to implement simple 2D collision detection of rectangles as follows:

  1. Make my own Collision detection class that extends Rectangle class.
  2. Then when instantiating that object doing something such as Collision col = new Rectangle(); <- Should I do that or is that something that should be avoided? I am aware that I 'can' but should I?
  3. I want to extend Rectangle class because of the contains() and intersects() methods; should I be doing that or should I be doing something else for 2D collision detection in Java?

Solution

  • you can easily extend Rectangle

    class CollidableRectangle extends Rectangle
    {
      public boolean isCollidingWith(Rectangle otherRect)
      {
        //check collision
      }
    
      // return all collisions
      public List<CollidableRectangle> getCollisions(List<Rectangle)
      {
        // code
      }
    }
    

    then you would use it like:

    CollidableRectangle r1 = new CollidableRectangle();
    CollidableRectangle r2 = new CollidableRectangle();
    
    r1.isCollidingWith(r2);
    
    //and so on
    

    As noted in comments I didn't use a Collision class. Usually you need it because you are also interested in collision parameters like depth or colliding plane so you would have something like:

    class Collision
    {
       CollidableRectangle first, second;
       float depth;
       Line2D collidingLine;
    }
    

    and the method would return a list of collisions:

    public List<Collision> getCollisions(List<Rectangle) { ... }