You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
love2d-tank/bullet.lua

87 lines
1.9 KiB

Bullet = Object:extend()
cos = math.cos
sin = math.sin --optimisation
function Bullet:new(x, y, p, speed, rotation)
self.image = love.graphics.newImage("assets/bullet.png")
self.x = x
self.y = y
self.p = p
self.speed = speed
self.rotation = rotation
self.width = self.image:getWidth()
self.height = self.image:getHeight()
self.scaleX = 1
self.scaleY = 1
self.originX = self.width / 2
self.originY = self.height / 2
self.collider = World:newCircleCollider(x, y, 10)
self.collider:setPosition(self.x, self.y)
end
function Bullet:update(dt)
--New bullets are set to New Collision Class
--this is to make sure the bullet doesn't collide with the player that shot it
if self.p == 1 or self.p == 2 then
self.collider:setCollisionClass("New")
end
if self.p == 1 then
self.collider:setCollisionClass("Bullet1")
elseif self.p == 2 then
self.collider:setCollisionClass("Bullet2")
end
if self.p == 1 then
local dx = cos(self.rotation) * self.speed * dt
local dy = sin(self.rotation) * self.speed * dt
self.collider:setLinearVelocity(dx, dy)
self.x = self.collider:getX()
self.y = self.collider:getY()
--If a bullet hits a wall, make it bounce off the wall and change its rotation
if self.collider:enter("Wall") then
self.rotation = self.rotation + math.pi
self.collider:setAngle(self.rotation)
end
end
if self.p == 2 then
local dx = cos(self.rotation) * self.speed * dt
local dy = sin(self.rotation) * self.speed * dt
self.collider:setLinearVelocity(dx, dy)
self.x = self.collider:getX()
self.y = self.collider:getY()
end
end
function Bullet:draw()
for _, _ in ipairs(Bullets1) do
love.graphics.draw(
self.image,
self.x,
self.y,
self.rotation,
self.scaleX,
self.scaleY,
self.originX,
self.originY
)
end
for _, _ in ipairs(Bullets2) do
love.graphics.draw(
self.image,
self.x,
self.y,
self.rotation,
self.scaleX,
self.scaleY,
self.originX,
self.originY
)
end
end