As stated by Sky_Render, there is a lot of ways to implement this and I too recommend reading up on
Lua Tables I find using metatables very handy for stuff like this, but that is more advanced and might be confusing if you're new to Lua.
My understanding of your game is similar to games where you move the player around and collect coins that are stationary. Below is some pseudocode.
Code: Select all
-- Collision detection function;
-- Returns true if two boxes overlap, false if they don't;
-- x1,y1 are the top-left coords of the first box, while w1,h1 are its width and height;
-- x2,y2,w2 & h2 are the same, but for the second box.
function CheckCollision(x1,y1,w1,h1, x2,y2,w2,h2) -- taken from https://www.love2d.org/wiki/BoundingBox.lua
return x1 < x2+w2 and
x2 < x1+w1 and
y1 < y2+h2 and
y2 < y1+h1
end
function love.load()
enemyType1 = {
-- just a list of important things about your enemy.
-- This example is just dimensions
width = 20,
height = 20
}
enemies = {} -- empty to start here
player = {
x = 150,
y = 150,
width = 50,
height = 50
}
local spawn = 10 -- total number of enemies to spawn
for i = 1, spawn do
-- put new enemies information into table.
table.insert(enemies, {
x = math.random(1, width), -- set coords
y = math.random(1, height),
width = enemyType1.width, -- set dimensions
height = enemyType1.height
})
end
end
function love.update(dt)
for k,v in pairs(enemies) do -- loop through all enemies.
if CheckCollision(player.x, player.y, player.width, player.height, -- pass player info
v.x, v.y, v.width, v.height) then -- pass info about each enemy
table.remove(enemies, k) -- remove the enemy from the list.
end
end
end
function love.draw()
-- draw it how you'd like
end
There are certainly better ways to do it, but this would work. The CheckCollision is only for two rectangles. Other algorithms will be needed for other types of geometry collisions.