【问题标题】:Circle rect collision detection not working in Corona SDK圆形矩形碰撞检测在 Corona SDK 中不起作用
【发布时间】:2011-08-22 00:22:44
【问题描述】:

我需要在我的游戏中摆脱物理,所以我需要实现一个自定义碰撞检测函数(碰撞检测函数每帧都被调用)。我想检查一个矩形是否与一个圆相交。我从here(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));
}

并改成这样:

--Collision detection between circle and 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,但我可能是错的)。我在转换过程中做错了吗?

【问题讨论】:

    标签: lua collision-detection coronasdk


    【解决方案1】:

    改变这两行:

        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)
    

    似乎可以解决问题。随机猜测万岁!

    【讨论】:

    • 另外,还有一种特殊情况没有处理:如果整个矩形都在圆内。如果必须处理这种情况,我会看看 distRC
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多