2PlayerShooter/bullet.lua
2024-04-21 19:28:24 +01:00

76 lines
1.8 KiB
Lua

Bullet = Object:extend()
function Bullet:new(x, y, p, image)
self.image = love.graphics.newImage(image)
self.x = x
self.y = y
self.p = p
self.width = self.image:getWidth()
self.height = self.image:getHeight()
end
function Bullet:update(dt)
local bulletspeed = 1200
--if bullet belongs to player 1, travel upwards
if self.p == 1 then
self.y = self.y - (bulletspeed * dt)
--if bullet belongs to player 2, travel downwards
elseif self.p == 2 then
self.y = self.y + (bulletspeed * dt)
end
--check if the bullet has hit a player
if self.p == 1 then
if
self.x < UserPlayer2.x + UserPlayer2.width
and UserPlayer2.x < self.x + self.width
and self.y < UserPlayer2.y + UserPlayer2.height
and UserPlayer2.y < self.y + self.height
then
UserPlayer2.health = UserPlayer2.health - 1
GameSounds.hit:play()
Bullets1 = {}
end
end
--check if the bullet has hit a player
if self.p == 2 then
if
self.x < UserPlayer1.x + UserPlayer1.width
and UserPlayer1.x < self.x + self.width
and self.y < UserPlayer1.y + UserPlayer1.height
and UserPlayer1.y < self.y + self.height
then
UserPlayer1.health = UserPlayer1.health - 1
GameSounds.hit:play()
Bullets2 = {}
end
end
--check if the bullet has hit a wall
for _, v in ipairs(Walls) do
if self.x < v.x + v.w and v.x < self.x + self.width and self.y < v.y + v.h and v.y < self.y + self.height then
if self.p == 1 then
Bullets1 = {}
elseif self.p == 2 then
Bullets2 = {}
end
GameSounds.hit:play()
end
end
end
function Bullet:clear()
Bullets1 = {}
Bullets2 = {}
end
function Bullet:draw()
for _, v in ipairs(Bullets1) do
love.graphics.draw(self.image, self.x, self.y)
end
for _, v in ipairs(Bullets2) do
love.graphics.draw(self.image, self.x, self.y)
end
end