圆形和矩形在Corona SDK中的碰撞检测无法正常工作。

我需要在我的游戏中取消物理功能,因此我需要实现一个自定义的碰撞检测函数(该碰撞检测函数每帧都会被调用)。我想检查一个矩形是否与一个圆相交。我从 这里(e.James 的回答)中取得了代码:

bool intersects(CircleType circle, RectType rect)
{
    circleDistance.x = abs(circle.x - rect.x - rect.width/2);
    circleDistance.y = abs(circle.y - rect.y - rect.height/2);

    if (circleDistance.x > (rect.width/2 + circle.r)) { return false; }
    if (circleDistance.y > (rect.height/2 + circle.r)) { return false; }

    if (circleDistance.x <= (rect.width/2)) { return true; }
    if (circleDistance.y <= (rect.height/2)) { return true; }

    cornerDistance_sq = (circleDistance.x - rect.width/2)^2 +
                         (circleDistance.y - rect.height/2)^2;

    return (cornerDistance_sq <= (circle.r^2));
}

我将其改为:

--Circle和Rect之间的碰撞检测
local function intersects(circle, rect)
    if circle ~= nil then
        local circleDistance_x = math.abs(circle.x - rect.x - rect.width/2);
        local circleDistance_y = math.abs(circle.y - rect.y - rect.height/2);

        if (circleDistance_x > (rect.width/2 + circle.r)) then
            return false
        end
        if (circleDistance_y > (rect.height/2 + circle.r)) then
            return false
        end

        if (circleDistance_x <= (rect.width/2)) then
            return true
        end

        if (circleDistance_y <= (rect.height/2)) then
            return true
        end

        cornerDistance_sq = (circleDistance_x - rect.width/2)^2 +
                             (circleDistance_y - rect.height/2)^2;

        return (cornerDistance_sq <= (circle.r^2));
        else
            return false
    end
end

我确保给圆形加上了一个 r 属性,设置为 20。我没有收到任何错误。并且当矩形靠近圆形时它们会被移除(似乎当矩形撞击圆形中心时函数返回 true,但我可能是错的)。我的转换做错了吗?

原文链接 https://stackoverflow.com/questions/7142088

点赞
stackoverflow用户667648
stackoverflow用户667648

改变这两行代码:

    local circleDistance_x = math.abs(circle.x - rect.x - rect.width/2);
    local circleDistance_y = math.abs(circle.y - rect.y - rect.height/2);

为:

    local circleDistance_x = math.abs(circle.x+circle.r - rect.x - rect.width/2)
    local circleDistance_y = math.abs(circle.y+circle.r - rect.y - rect.height/2)

似乎解决了这个问题。为猜测而欢呼!

2011-08-22 00:39:55