Skip to content

Instantly share code, notes, and snippets.

@sonic2kk
Last active August 29, 2015 14:25
Show Gist options
  • Save sonic2kk/0649d5942a244960f0cb to your computer and use it in GitHub Desktop.
Save sonic2kk/0649d5942a244960f0cb to your computer and use it in GitHub Desktop.
Simple Lua function for detecting circle/rectangle collision
local math_abs = math.abs
function circlerect_colliding(cx, cy, cr, rx, ry, rw, rh)
circleDistance_x = math_abs(cx - rx)
circleDistance_y = math_abs(cy - ry)
if circleDistance_x > (rw / 2 + cr) then
return false
end
if circleDistance_y > (rh / 2 + cr) then
return false
end
if circleDistance_x <= (rw / 2) then
return true
end
if circleDistance_y <= (rh / 2) then
return true
end
cornerDistance_sq = (circleDistance_x - rw / 2) ^ 2 + (circleDistance_y - rh / 2) ^ 2
return (cornerDistance_sq <= (cr ^ 2))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment