| Forum Home > Turing > Collision Test - Point to Rectangle | ||
|---|---|---|
|
Moderator Posts: 8 |
How to Check Collision Between a Point and a Rectangle Theory Lets define the variables as px, py for the point, and x1, y1, x2, y2 for the rectangle. Note the following restriction: x1 <= x2, and y1 <= y2. This must be satisfied for this algorithm to work.
We can make a few notes:
We can then turn this information into code... if px >= x1 && px <= x2 && py >= y1 && py <= y2 then % collision else % no collision end if Note we can also do the reverse, and test for a non-collision. If we know that px must be >= x1 and <= x2, that means if px is either < x1, or px is > x2, there cannot be a collision. We can also make the same conclusion in the y coordinate, if py must be >= y1, and py <= y2, then there can be no collision if py < y1, or py > y2. if px < x1 || px > x2 || py < y1 || py > y2 then % no collision else % collision end if This, believe it or not, is actually more efficient. With this method, if any part of it is false, we know already it is impossible to have a collision. Therefore, at best, only 1 comparison is made, and at worst, 4. With the previous methed, all 4 comparisons must be verified to be sure that a collision is made. Recall the restriction that x1 <= x2, meaning x1 must be the left side of the rectangle, and x2 must be the right side. also, y1 <= y2, meaning y1 must be the bottom side, and y2 the top side. If needed, you may make an additional check: function pointIntersectsRectangle (px : int, py : int, x1 : int, y1 : int, x2 : int, y2 : int) : boolean % Ensures x1 <= x2, and y1 <= y2 var Rx1, Ry1, Rx2, Ry2 : int Rx1 := min (x1, x2) Ry1 := min (y1, y2) Rx2 := max (x1, x2) Ry2 := max (y1, y2) result not (px < Rx1 || px > Rx2 || py < Ry1 || py > Ry2) end pointIntersectsRectangle
| |
| ||