Search code examples
javacollision-detectioncollision

I have two squares drawn on the screen, how can I detect collision on the edges of both objects?


Right now, I can compare the X and Y to check for collision, but that's only if the two objects pass right through each other, on exactly the same X & Y pos. I need to check for collisions a little more precisely, to check for skims, for lack of a better term. I have variables for the X, Y, X and Y Scales and the velocity for X and Y. Any help is much appreciated :D

EDIT: The squares!!!


Solution

  • If your squares can't rotate, it's easy: say double r is the length of every edge, Point p1 is the center of one square, and p2 is of the other. then:

    if (Math.abs(p1.x - p2.x) < r && Math.abs(p1.y - p2.y) < r) {
        // Collision
    }
    

    The more complex case is if a square might be rotated. In such case: treat each edge of the objects as a geometric line (you can easily compute each line's equation if you know the coordinates of the corners).

    Next, find the meeting point of every couple of lines (each from one square against each from the other one), and test if this point is inside one of the squares. If one of those comparisons return true - a collision occurred.