Re: New to lua, need help with tables (and now collisions)
Posted: Thu Oct 28, 2010 10:04 am
First of all, create a function to handle your collision checking. That will make things a lot more readable. For example, this one (you're welcome) checks a rectangle against a circle (which seems like what you want to do):
Then you would do something like this:
Code: Select all
function circRectCollision(rectx, recty, rectwidth, rectheight, pointx, pointy, radius)
local pow = math.pow
local root = math.sqrt
--Check if the projectile is inside the enemy bounding box
if pointx > rectx-radius and pointy > rectyy-radius and pointx < rectx+rectwidth+radius and pointy < recty+rectheight+radius then
return true
--Check if the projectile is touching the corner of the rect bounding box
elseif root( pow( rectx-pointx, 2 ) + pow( recty-pointy, 2 ) ) < radius or
root( pow( rectx+rectwidth-pointx, 2 ) + pow(recty-pointy, 2 ) ) < radius or
root( pow( rectx-pointx, 2 ) + pow( recty+rectheight-pointy, 2 ) ) < radius or
root( pow( rectyx+rectwidth-pointx, 2 ) + pow( recty+rectheight-pointy, 2 ) ) < radius then
return true
end
end
Code: Select all
function love.update(dt)
local enemyremovetable = {}
local projectileremovetable = {}
for i,v in ipairs(enemies) do
for n,k in ipairs(projectiles) do
if circRectCollision( v.x, v.y, 32, 32, k.x, k.y, 1 ) then
table.insert(enemyremovetable, i)
table.insert(projectileremovetable, n)
end
end
end
for i,v in ipairs(enemyremovetable) do
table.remove(enemies, v-i+1)
end
for i,v in ipairs(projectileremovetable) do
table.remove(projectiles, v-i+1)
end
end