1
我需要擺脫我遊戲中的物理因素,因此我需要實現自定義碰撞檢測功能(每幀調用碰撞檢測功能)。我想檢查矩形是否與圓相交。我從here代碼(答案由e.James):Circle Corct碰撞檢測在Corona SDK中不起作用
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,但我可能是錯的)。我在轉換中做錯了什麼?
此外,還有一個特殊情況未處理:如果整個矩形位於圓內。如果必須處理這種情況,我會看到distRC <= radius其中distRC是從圓心到矩形中心的距離。 – Gareve