我需要在游戏中摆脱物理因素,因此我需要实现自定义碰撞检测功能(每帧都会调用碰撞检测功能)。我想检查矩形是否与圆相交。我从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,但我可能错了)。我在转换中做错了吗?
答案 0 :(得分: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)
似乎要做的伎俩。 Hurray随机猜测!