0
\$\begingroup\$

I have a list of lazers(bullets) that i would like to delete specific instances from. How would I go about doing that with the code I have now? I first tried to pass in the player to a lazer instance and if that lazers out of bounds delete by indexing the lazer table with its id and setting that to nil. But then the lazers stopped working with that logic. Setting lazer to nil inside its own update function doesnt work either.(self = nil)

Lazer = Class("Lazer")
Lazer.isLazer = true
Lazer.count = 0
function Lazer:init(x,y,speed,rax,ray)
    self.position = Vector2(x,y)
    self.speed = speed
    self.velocity = Vector2(rax,ray):unit()
    self.id = Lazer.count
    Lazer.count = Lazer.count + 1
end
function Lazer:update(dt)
    self.position = self.position + self.velocity * self.speed * dt
    if not isPointWithinRect(self.position.x,self.position.y,0,0,windowWidth,windowHeight) then
       --what do i do here?
    end
end
function Lazer:draw()
    love.graphics.setColor(255,255,0)
    love.graphics.circle("line",self.position.x,self.position.y,5,5)
end

Player = Class("Player")
Player.isPlayer = true
function Player:init(joystick,x,y,speed)
    self.joystick = joystick
    self.position = Vector2(x,y)
    self.velocity = Vector2(0,0)
    self.speed = speed
    self.acceleration = acceleration
    self.terminal_velocity = terminal_velocity
    self.lazzer_speed = speed + 25
    self.lazers = {}
    self.timer = 0
end
function Player:update(dt)
    self.timer = self.timer + dt
    local lax,lay = self.joystick:getAxes()
    self.velocity.x = lax
    self.velocity.y = lay
    if math.abs(lax) > .1 or math.abs(lay) > .1 then
        self.velocity = self.velocity:unit()
    end
    self.position = self.position + self.velocity * self.speed * dt
    self.position.x = clamp(self.position.x,0 + 20,windowWidth - 20)
    self.position.y = clamp(self.position.y,0 + 20,windowHeight - 20)
    local _,_,rax,ray = self.joystick:getAxes()
    if (math.abs(rax) > .1 or math.abs(ray) > .1) and self.timer > .1 then
        table.insert(self.lazers,Lazer(self.position.x,self.position.y,self.speed + 250,rax,ray))
        self.timer = 0
    end
    for _,v in pairs(self.lazers) do
        v:update(dt)
    end
end
function Player:draw()
    love.graphics.setColor(255,255,255,255)
    love.graphics.circle("line",self.position.x,self.position.y,15,30)
    for _,v in pairs(self.lazers) do
        v:draw()
    end
end
``` 
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.