So let's get to the point, my real problem is my collision works but when my bullet collides with the enemy sometimes it deletes the enemy and sometimes not. I'm really confuse and I don't know what to do, I have been fixing and searching some solutions online like non stop but I can't find a working one so I decided to register on the forum and find some help.
Code: Select all
--Requirements Importer
local Chrono = require("utils/chrono")
--Main
function love.load()
timer = Chrono()
player = {}
player.x = 250
player.y = 590
player.cooldown = 15
player.width = 0.1
player.height = 0.1
player.image = love.graphics.newImage("images/spaceship.png")
player.bullets = {}
enemies = {}
enemies.army = {}
function player.shoot()
if player.cooldown < 0 then
player.cooldown = 15
bullet = {}
bullet.x = player.x - 30
bullet.y = player.y - 50
table.insert(player.bullets, bullet)
end
end
function enemies.spawn()
enemy = {}
enemy.x = math.random(0, 700)
enemy.y = 10
enemy.width = 1
enemy.height = 1
enemy.image = love.graphics.newImage("images/enemy.png")
table.insert(enemies.army, enemy)
end
timer:every(2, function()
enemies.spawn()
end)
end
function love.update(dt)
timer:update(dt)
player.cooldown = player.cooldown - 1
if love.keyboard.isDown("escape") then
love.event.quit()
elseif love.keyboard.isDown("left") then
if player.x > 50 then
player.x = player.x - 8
end
elseif love.keyboard.isDown("right") then
if player.x < 800 then
player.x = player.x + 8
end
end
for i,v in pairs(player.bullets) do
v.y = v.y - 10
end
for i,v in pairs(enemies.army) do
v.y = v.y + 3
end
for i, e in pairs(enemies.army) do
for _, b in pairs(player.bullets) do
if CheckCollision(b.x, b.y, 10, 10, e.x, e.y, enemy.width, enemy.height) then
table.remove(enemies.army, i)
end
end
end
end
function CheckCollision(x1,y1,w1,h1, x2,y2,w2,h2)
return x1 < x2+w2 and
x2 < x1+w1 and
y1 < y2+h2 and
y2 < y1+h1
end
function love.draw()
love.graphics.draw(player.image, player.x, player.y, math.pi, player.width, player.height)
love.graphics.print("Player location:"..player.x.." | "..player.y)
for i,v in pairs(player.bullets) do
if v.y < 0 then
table.remove(player.bullets, i)
end
love.graphics.setColor(255, 255, 255)
love.graphics.rectangle("fill", v.x, v.y, 10, 10)
end
for i,v in pairs(enemies.army) do
love.graphics.setColor(77, 255, 0)
love.graphics.draw(v.image, v.x, v.y, 1, 0.1)
end
end
function love.keypressed(key, scancode, isrepeat)
if key == "space" then
player.shoot()
end
end