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

前端 未结 3 1096
天命终不由人
天命终不由人 2021-01-29 11:36

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 chec

3条回答
  •  我在风中等你
    2021-01-29 12:10

    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.

提交回复
热议问题