I have a table of every enemy on the screen, enemies.onscreen. I have another table for every projectile launched by the user (projectiles.playershots). For each enemy on the screen I want to check if it is currently colliding with one of the projectiles. Here's how I've done it:
Code: Select all
--this is in love.update()
for i,v in ipairs(enemies.onscreen) do
local enemywidth = enemies.types[v.type].width/2 --Get the height and width of the enemy sprite, so that we can add an offset
local enemyheight = enemies.types[v.type].height/2
for n,c in ipairs(projectiles.playershots) do
--The sprite origin is centered on the sprite, so we need to add offsets for all sides.
if collision({v.x-enemywidth, v.x+enemywidth, v.x+enemywidth, v.x-enemywidth}, {v.y-enemyheight, v.y-enemyheight, v.y+enemyheight, v.y+enemyheight}, c.position.x, c.position.y, player.images.shot.width/2) then
table.remove(v, i)
table.remove(c, n)
end
end
end
--this function is not in love.update(), naturally
function collision(x, y, pointx, pointy, radius) --takes two tables, one for the c-coordinates of the enemy's four corners, and one for the y-coordinates. The rest is the projectile's coordinates and radius.
local pow = math.pow
local root = math.sqrt
for i,v in ipairs(x) do
if root( pow( (pointy-y[i]),2) + pow( (pointx-v),2 ) ) < radius then --Check if the distance between the projectile and the nearest corner is less than the radius of the projectile
return true
end
end
end
In case it might be helpful, here's the data structure of the projectiles and the enemies.
Code: Select all
--Projectiles
projectiles = {
playershots = {}
}
--Every time a shot is fired, it is created like this
table.insert(projectiles.playershots, {
start={ -- The starting point of the projectile
x=player.x,
y=player.y
},
target = { --Where it's headed
x=x,
y=y
},
position={ -- Current position
x=player.x,
y=player.y
},
direction = math.atan2((y-player.y),(x-player.x)), --The direction in which it is travelling
v = 5 --speed
})
Code: Select all
--Enemies
enemies = {
types = {
{
name = "ufo",
sprite = love.graphics.newImage("images/enemies/ufo.png"),
width, height,
health = 10,
v = 100
}
},
onscreen = {}
}
--Whenever an enemy is created, this is run
function createRandEnemy()
local randint = math.random
local scaling = randint(75,125)/100
return {
type = randint(1 , table.getn(enemies.types) ),
x = randint(50, screenWidth-50),
y = -100,
rotation = 0.0, --not used currently
scale = {
x = scaling,
y = scaling,
},
speed = 50,
}
end