Collision = {} local sqrt = math.sqrt function Collision.pointInRect( pointX, pointY, left, top, width, height ) if pointX >= left and pointX <= left + width and pointY >= top and pointY <= top + height then return true else return false end end function Collision.pointInCircle( pointX, pointY, centerX, centerY, radius ) local dX, dY = pointX - centerX, pointY - centerY if dX * dX + dY * dY <= radius * radius then return true else return false end end function Collision.rectAndCircle(rect, centerX, centerY, radius) return Collision.boxAndCircle(rect:getX(), rect:getY(), rect:getWidth(), rect:getHeight(), centerX, centerY, radius) end function Collision.boxAndCircle(x, y, width, height, centerX, centerY, radius) local closestX = centerX local closestY = centerY --Closest x if( centerX < x) then closestX = x elseif (centerX > x + width) then closestX = x + width end --Closest y if( centerY < y) then closestY = y elseif (centerY > y + height) then closestY = y + height end if (Collision.distance(centerX, centerY, closestX, closestY) < radius * radius) then return true else return false end end function Collision.rectAndRect(rect1, rect2) local x1, y1, w1, h1 = rect1:getX(), rect1:getY(), rect1:getWidth(), rect1:getHeight() local x2, y2, w2, h2 = rect2:getX(), rect2:getY(), rect2:getWidth(), rect2:getHeight() return x1 < x2 + w2 and x2 < x1 + w1 and y1 < y2 + h2 and y2 < y1 + h1 end function Collision.circleAndCircle(x1, y1, radius1, x2, y2, radius2) return sqrt(Collision.distance(x1, y1, x2, y2)) < radius1 + radius2 end function Collision.closest(centerX, centerY, radius, brick) local closestX = centerX local closestY = centerY --Closest x if( centerX < brick:getX()) then closestX = brick:getX() elseif (centerX > brick:getX() + brick:getWidth()) then closestX = brick:getX() + brick:getWidth() end --Closest y if( centerY < brick:getY()) then closestY = brick:getY() elseif (centerY > brick:getY() + brick:getHeight()) then closestY = brick:getY() + brick:getHeight() end return closestX, closestY end function Collision.distance(x1, y1, x2, y2) return math.pow( x2 - x1, 2 ) + math.pow( y2 - y1, 2 ) --return math.sqrt( math.pow( x2 - x1, 2 ) + math.pow( y2 - y1, 2 ) ); end