简体   繁体   中英

Circle rect collision detection not working in Corona SDK

I needed to get rid of physics in my game so I needed to implement a custom collision detection function (the collision detection function is being called every frame). I want to check if a rectangle has intersected a circle. I took the code from here (the answer by 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));
}

And changed it to this:

--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

I made sure to give the circle a r property and made it 20. I am not getting any errors. And the rectangles are removed when they get near the circle (it seems like the function returns true when the rectangle hits the center of the circle but I may be wrong). Am I doing something wrong in my conversion?

Changing these two lines:

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

To:

    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)

Seems to do the trick. Hurray for random guessing!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM