Created
January 3, 2014 22:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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