Search code examples
javaswingcollision-detectionjava-2d

Java2D Distance Collision Detection


My current setup is only useful once collision has been made; obviously there has to be something better than this?

public boolean CollisionCheck(Rectangle rect1, Rectangle rect2) {
   if(rect1.intersects(rect2)) {
      return true;
   }
   return false;
}

How can I do preemptive collision detection?


Solution

  • Generally, you pre-compute one step ahead, something like this:

    Inside Rectangle class:

    public void move()
    {
        rec.x += rec.dx
        rec.y += rec.dy
    }
    

    Then,

    public boolean CollisionCheck(Rectangle rect1, Rectangle rect2) {
       rec1.move();
       rec2.move();
       if(rect1.intersects(rect2)) {
          return true;
       }
       return false;
    }
    

    Ha. Travis got in before I did. Nice to see SO has update answer notifications.