如何检测移动点与固定矩形的碰撞入射方向
点与矩形碰撞的入射方向检测实现方案
要实现该功能的核心前提是:你需要存储点上一帧的坐标,只有拿到点的移动轨迹,才能判断具体的入射方向。
核心逻辑
- 先确认碰撞是刚发生的:上一帧点在矩形外部,当前帧点在矩形内部,排除点本来就在矩形内的情况。
- 通过点的历史位置和矩形四条边的位置关系,判断点具体穿过了哪条边进入矩形。
- 针对斜向撞角的特殊场景,通过移动分量的占比判断主入射方向。
完整实现代码
def pointRect(px, py, rx, ry, rw, rh): # 判断点是否在矩形内部 if (px >= rx and px <= rx + rw and py >= ry and py <= ry + rh): return True return False def getCollisionDirection(prev_px, prev_py, curr_px, curr_py, rx, ry, rw, rh): # 未发生碰撞直接返回 if not pointRect(curr_px, curr_py, rx, ry, rw, rh): return None # 上一帧已在矩形内,不是刚发生的碰撞,直接返回 if pointRect(prev_px, prev_py, rx, ry, rw, rh): return None # 矩形四条边的坐标 left_edge = rx right_edge = rx + rw top_edge = ry bottom_edge = ry + rh # 点的移动分量 dx = curr_px - prev_px dy = curr_py - prev_py # 分别判断各边的碰撞情况 hit_top = prev_py < top_edge and curr_py >= top_edge and left_edge <= curr_px <= right_edge hit_bottom = prev_py > bottom_edge and curr_py <= bottom_edge and left_edge <= curr_px <= right_edge hit_left = prev_px < left_edge and curr_px >= left_edge and top_edge <= curr_py <= bottom_edge hit_right = prev_px > right_edge and curr_px <= right_edge and top_edge <= curr_py <= bottom_edge # 单一边碰撞的常规场景 if hit_top: return "top" if hit_bottom: return "bottom" if hit_left: return "left" if hit_right: return "right" # 撞角的特殊场景,按移动分量占比判断主入射方向 if abs(dx) > abs(dy): return "left" if dx > 0 else "right" else: return "top" if dy > 0 else "bottom"
适用说明
以上实现没有复杂计算,性能很高,足够覆盖绝大多数2D游戏、图形交互场景的需求。如果你的场景对撞角方向的精度要求极高,可以进一步计算移动向量和矩形各边法向量的点积,点积最小的边即为碰撞边。
内容的提问来源于stack exchange,提问作者eddiewastaken
相关产品推荐
相关产品推荐

