2011-08-22 76 views
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,但我可能是错的)。我在转换中做错了什么?

回答

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) 

似乎这样的伎俩。欢呼随机猜测!

+0

此外,还有一个特殊情况未处理:如果整个矩形位于圆内。如果必须处理这种情况,我会看到distRC <= radius其中distRC是从圆心到矩形中心的距离。 – Gareve