## Collision Explanation

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
SuperMeijin
Prole
Posts: 15
Joined: Wed Oct 03, 2012 3:37 pm

### Collision Explanation

This is my collision function

Code: Select all


for ii,vv in ipairs(enemies) do -- shot:enemy collision for zombies
if CheckCollision(v.x,v.y,16,16,vv.x,vv.y,vv.width,vv.height) then
table.insert(remEnemy, ii)
table.insert(remShot, i)

I dont really understand whats going on in this CheckCollision function but my enemies seem to collide at the wrong points and a bit randomly.

As a extension if i want my enemies to face me at all time how would i change this function to fit the way there facing

Checkcollision

Code: Select all

function CheckCollision(ax1,ay1,aw,ah, bx1,by1,bw,bh)

local ax2,ay2,bx2,by2 = ax1 + aw, ay1 + ah, bx1 + bw, by1 + bh
return ax1 < bx2 and ax2 > bx1 and ay1 < by2 and ay2 > by1
end
William Willing
Prole
Posts: 7
Joined: Mon Jan 07, 2013 8:48 pm

### Re: Collision Explanation

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.

### Who is online

Users browsing this forum: Bing [Bot] and 18 guests