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

90 lines
1.9 KiB

5 months ago
Bullet = Object:extend()
4 months ago
cos = math.cos
sin = math.sin --optimisation
pi = math.pi
5 months ago
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
4 months ago
self.collider = World:newCircleCollider(x, y, 10)
self.collider:setFixedRotation(true)
5 months ago
self.collider:setPosition(self.x, self.y)
if self.p == 1 then
self.collider:setCollisionClass("Bullet1")
elseif self.p == 2 then
self.collider:setCollisionClass("Bullet2")
end
end
5 months ago
function Bullet:update(dt)
--If a bullet hits a wall, make it bounce off the wall and change its rotation
5 months ago
if self.p == 1 then
4 months ago
if self.collider:enter("Wall") then
--calculate normal of the wall
--calculate the angle of reflection
local angle = (math.atan2(dx, dy))
--get normal of the wall without using getNormal()
----TODO: fix this
--set the new angle
self.rotation = angle
4 months ago
self.collider:setAngle(self.rotation)
end
dx = cos(self.rotation) * self.speed * dt
dy = sin(self.rotation) * self.speed * dt
self.collider:setLinearVelocity(dx, dy)
5 months ago
end
if self.p == 2 then
4 months ago
local dx = cos(self.rotation) * self.speed * dt
local dy = sin(self.rotation) * self.speed * dt
self.collider:setLinearVelocity(dx, dy)
5 months ago
end
self.x = self.collider:getX()
self.y = self.collider:getY()
5 months ago
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