Hi,
I’m a newbie to Corona, but I am a Mathematics student so know my way around the geometry in collision detection (or at least I like to think I do). I am making a game and it needs to detect collisions between rotated rectangles, after looking on the internet I found a lot of people have the same problem. The separating axis theorem is often suggested as advice, but I imagine its complexity puts people off.
So here is my code for the collision detection:
local function isCollision( x10, y10, height1, width1, radrot1, x20, y20, height2, width2, radrot2 ) --x10, y10 is centre point of rect1. x20, y20 is centre point of rect2 --height1, width1 are half heights/widths of rect1, radrot is rotation of rect in radians local radius1 = math.sqrt( height1\*height1 + width1\*width1 ) local radius2 = math.sqrt( height2\*height2 + width2\*width2 ) local angle1 = math.asin( height1 / radius1 ) local angle2 = math.asin( height2 / radius2 ) local x1 = {}; local y1 = {} local x2 = {}; local y2 = {} x1[1] = x10 + radius1 \* math.cos(radrot1 - angle1); y1[1] = y10 + radius1 \* math.sin(radrot1 - angle1) x1[2] = x10 + radius1 \* math.cos(radrot1 + angle1); y1[2] = y10 + radius1 \* math.sin(radrot1 + angle1) x1[3] = x10 + radius1 \* math.cos(radrot1 + math.pi - angle1); y1[3] = y10 + radius1 \* math.sin(radrot1 + math.pi - angle1) x1[4] = x10 + radius1 \* math.cos(radrot1 + math.pi + angle1); y1[4] = y10 + radius1 \* math.sin(radrot1 + math.pi + angle1) x2[1] = x20 + radius2 \* math.cos(radrot2 - angle2); y2[1] = y20 + radius2 \* math.sin(radrot2 - angle2) x2[2] = x20 + radius2 \* math.cos(radrot2 + angle2); y2[2] = y20 + radius2 \* math.sin(radrot2 + angle2) x2[3] = x20 + radius2 \* math.cos(radrot2 + math.pi - angle2); y2[3] = y20 + radius2 \* math.sin(radrot2 + math.pi - angle2) x2[4] = x20 + radius2 \* math.cos(radrot2 + math.pi + angle2); y2[4] = y20 + radius2 \* math.sin(radrot2 + math.pi + angle2) local axisx = {}; local axisy = {} axisx[1] = x1[1] - x1[2]; axisy[1] = y1[1] - y1[2] axisx[2] = x1[3] - x1[2]; axisy[2] = y1[3] - y1[2] axisx[3] = x2[1] - x2[2]; axisy[3] = y2[1] - y2[2] axisx[4] = x2[3] - x2[2]; axisy[4] = y2[3] - y2[2] for k = 1,4 do local proj = x1[1] \* axisx[k] + y1[1] \* axisy[k] local minProj1 = proj local maxProj1 = proj for i = 2,4 do proj = x1[i] \* axisx[k] + y1[i] \* axisy[k] if proj \< minProj1 then minProj1 = proj elseif proj \> maxProj1 then maxProj1 = proj end end proj = x2[1] \* axisx[k] + y2[1] \* axisy[k] local minProj2 = proj local maxProj2 = proj for j = 2,4 do proj = x2[j] \* axisx[k] + y2[j] \* axisy[k] if proj \< minProj2 then minProj2 = proj elseif proj \> maxProj2 then maxProj2 = proj end end if maxProj2 \< minProj1 or maxProj1 \< minProj2 then return false end end return true end
If anyone wants to use this or give any suggestions then feel free. Main ideas used can be found here
Andy