如何基于碰撞盒边界数据精确检测双精度坐标矩形相交?
Detecting Axis-Aligned Rectangle Intersection with Double-Precision Coordinates
Hey there! Based on the hitbox boundary values you’ve calculated (the min/max X and Y for both target and source rectangles), checking for intersection is a breeze using a "rule out the non-overlaps" approach.
The core idea is simple: two axis-aligned rectangles do not intersect if one is completely to the left, right, above, or below the other. If none of these four conditions are true, the rectangles must overlap (or touch, depending on how you define intersection).
The Check Logic
First, let’s fill in the missing bounds variables from your snippet, then implement the intersection check:
// Your existing boundary calculations final double targetSmallestX = targetCenter.getX() - targetHalfWidth; final double targetSmallestY = targetCenter.getY() - targetHalfHeight; final double targetHighestX = targetCenter.getX() + targetHalfWidth; final double targetHighestY = targetCenter.getY() + targetHalfHeight; final double sourceSmallestX = sourceCenter.getX() - sourceHalfWidth; final double sourceSmallestY = sourceCenter.getY() - sourceHalfHeight; final double sourceHighestX = sourceCenter.getX() + sourceHalfWidth; // Missing in your snippet final double sourceHighestY = sourceCenter.getY() + sourceHalfHeight; // Missing in your snippet // Check if rectangles are completely separate (disjoint) boolean areDisjoint = sourceHighestX < targetSmallestX || // Source is entirely left of target sourceSmallestX > targetHighestX || // Source is entirely right of target sourceHighestY < targetSmallestY || // Source is entirely above target sourceSmallestY > targetHighestY; // Source is entirely below target // If they're NOT disjoint, they intersect boolean doIntersect = !areDisjoint;
Key Notes
- Edge Case Handling: The code above treats "touching" rectangles (edges meeting but no overlap) as non-intersecting. If you want to count touching as an intersection, replace
<with<=and>with>=in the disjoint check. - Axis-Aligned Only: This logic works for rectangles aligned with the X/Y axes (which your center/half-width setup assumes). For rotated rectangles, you’ll need the separating axis theorem—let me know if you need help with that!
- Floating-Point Precision: Using
doubleis totally safe here. Just avoid exact equality checks (we don’t use any here) to prevent issues with floating-point rounding errors.
内容的提问来源于stack exchange,提问作者Basti
相关产品推荐
相关产品推荐

