You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenGL 2D环境下Circle与Rotated AABB碰撞检测实现问题咨询

圆形与旋转矩形碰撞检测代码修复方案

你原思路的核心逻辑是成立的,将两个物体共同旋转至矩形和坐标轴对齐后调用Circle-AABB检测是该场景的标准实现方案之一,现有代码存在3个核心错误,修复如下:

  • 旋转坐标计算变量覆盖问题:计算新的circleY时误用了已经被修改后的circleX值,计算bottom时误用了修改后的left值,导致旋转后坐标完全错误
  • 旋转基准点错误:原有逻辑默认绕全局原点旋转,正确的旋转基准应该是矩形自身的中心,否则变换后矩形位置会完全偏移
  • 语法结构错误:函数提前闭合,后续碰撞检测逻辑写在了函数作用域外,无法正常执行

修复后完整代码

bool CheckCollision(float circleX, float circleY, float radius, float left, float bottom, float width, float height, float angle){
    // 计算矩形原始中心,作为旋转基准点
    float rectCenterX = left + width / 2.0f;
    float rectCenterY = bottom + height / 2.0f;
    float negAngle = -angle;
    float cosVal = cos(negAngle);
    float sinVal = sin(negAngle);

    // 仅需要将圆心绕矩形中心旋转-angle即可,旋转后矩形自动和坐标轴对齐,参数不变
    float relCircleX = circleX - rectCenterX;
    float relCircleY = circleY - rectCenterY;
    float rotatedCircleX = relCircleX * cosVal - relCircleY * sinVal + rectCenterX;
    float rotatedCircleY = relCircleX * sinVal + relCircleY * cosVal + rectCenterY;
    glm::vec2 center(rotatedCircleX, rotatedCircleY);

    // 旋转后矩形还是原来的中心和宽高,直接做Circle-AABB检测
    glm::vec2 aabb_half_extents(width / 2.0f, height / 2.0f);
    glm::vec2 aabb_center(rectCenterX, rectCenterY);
    glm::vec2 difference = center - aabb_center;
    glm::vec2 clamped = glm::clamp(difference, -aabb_half_extents, aabb_half_extents);
    glm::vec2 closest = aabb_center + clamped;
    difference = closest - center;

    return glm::length(difference) < radius;
}

内容的提问来源于stack exchange,提问作者Stefan Nastase

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:24:03