Skip to content

Instantly share code, notes, and snippets.

@robmiracle
Created January 3, 2014 22:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robmiracle/8247918 to your computer and use it in GitHub Desktop.
Save robmiracle/8247918 to your computer and use it in GitHub Desktop.
Two functions to test for collisions between rectangles and circles without needing physics.
-- rectangle based
local function hasCollided(obj1, obj2)
if obj1 == nil then
return false
end
if obj2 == nil then
return false
end
local left = obj1.contentBounds.xMin <= obj2.contentBounds.xMin and obj1.contentBounds.xMax >= obj2.contentBounds.xMin
local right = obj1.contentBounds.xMin >= obj2.contentBounds.xMin and obj1.contentBounds.xMin <= obj2.contentBounds.xMax
local up = obj1.contentBounds.yMin <= obj2.contentBounds.yMin and obj1.contentBounds.yMax >= obj2.contentBounds.yMin
local down = obj1.contentBounds.yMin >= obj2.contentBounds.yMin and obj1.contentBounds.yMin <= obj2.contentBounds.yMax
return (left or right) and (up or down)
end
 
-- circle based
local function hasCollidedCircle(obj1, obj2)
if obj1 == nil then
return false
end
if obj2 == nil then
return false
end
local sqrt = math.sqrt
 
local dx = obj1.x - obj2.x;
local dy = obj1.y - obj2.y;
 
local distance = sqrt(dx*dx + dy*dy);
local objectSize = (obj2.contentWidth/2) + (obj1.contentWidth/2)
if distance < objectSize then
return true
end
return false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment