I renamed the variables in the CheckCollision function. Hopefully, this makes things a bit clearer.
Code: Select all
function CheckCollision(aLeft, aTop, aWidth, aHeight, bLeft, bTop, bWidth, bHeight)
local aRight = aLeft + aWidth
local aBottom = aTop + aHeight
local bRight = bLeft + bWidth
local bBottom = bTop + bHeight
return aLeft < bRight and aRight > bLeft and aTop < bBottom and aBottom > bTop
end
I find it hard to check the code just by thinking about it, so I made a little drawing.
In this drawing, I only look at the logic for the x-axis. The logic for the y-axis is the same; just rotate the drawing 90 degrees. :-)
Your CheckCollision function only checks for two situations, but there are three situations in which A and B collide, so I suspect that your function is not complete. I find it easier to reason about when A and B do NOT collide, since there are only two possibilities for that: B is entirely to the left of A or B is entirely to the right of A. In code: bRight < aLeft or bLeft > aRight.
So, I think the following function should work. (I haven't really tested it, though.)
Code: Select all
function CheckCollision(aLeft, aTop, aWidth, aHeight, bLeft, bTop, bWidth, bHeight)
local aRight = aLeft + aWidth
local aBottom = aTop + aHeight
local bRight = bLeft + bWidth
local bBottom = bTop + bHeight
local horizontalCollision = not (bRight < aLeft or bLeft > aRight)
local verticalCollision = not (bBottom < aTop or bTop > aBottom)
return horizontalCollision and verticalCollision
end
Hope that helps.