1. 程式人生 > >碰撞檢測演算法:點和矩形碰撞、矩形碰撞

碰撞檢測演算法:點和矩形碰撞、矩形碰撞

以下程式碼Lua可直接除錯.

點與矩形碰撞

-- 點與矩形碰撞
function testPoint(x0,y0,w0,h0,x1,y1)
    return x1 >= x0 and x1 <= x0 + w0 and y1>=y0 and y1 < y0 + h0
end

矩形碰撞

-- 矩形碰撞
function testRect(x0,y0,w0,h0,x1,y1,w1,h1)
    return x0<x1+w1 and y0<y1+h1 and x0+w0>x1 and y0+h0>y1
end

圓形碰撞

-- 圓形碰撞
function testCircle
(x0,y0,r0,x1,y1,r1)
return math.sqrt(math.pow(math.abs(x0-x1),2)+math.pow(math.abs(y0-y1),2)) < r0+r1 end

點與圓形碰撞

-- 點與圓形碰撞
function testCircle(x0,y0,x1,y1,r1)
    return math.sqrt(math.pow(math.abs(x0-x1),2)+math.pow(math.abs(y0-y1),2)) < r1
end