0
votes

I'm making a space game using Corona Sdk and one of the functions in my code is used to fire laser beams. These beams are supposed to disappear when they finish their transition, but I have one problem: when I fire more than one at the same time (using a button widget(one per click)) only the last one fired disappears, right after the first one finishes its transition.

This is my code right now:

local function removeLaser(event)
    --[[
    this doesn't work -> display.remove(laser)
    this returns an error (main.lua:34: attempt to call method 'removeSelf' (a
    nil value)) -> laser.removeSelf()
    --]]
end

local function fire(event)
    laser=display.newImageRect("laser.png",75,25)
    laser.x=spaceship.contentWidth+spaceship.x/2+3
    laser.y=spaceship.y 
    transition.to(laser,{time=1000,x=display.contentWidth, onComplete=removeLaser})
end

local function createButton()
    buttonFire=widget.newButton
    {
        defaultFile="buttonUNP.png",
        overFile="buttonP.png",
        width=130,
        height=130,
        emboss=true,
        onPress=fire,
        id="buttonFire"
    }
    buttonFire.x=display.contentWidth-buttonFire.contentWidth/2-10
    buttonFire.y=display.contentHeight-buttonFire.contentHeight/2-10
end

What should I do about the function removeLaser(event)?

1

1 Answers

0
votes

Just put the removeLaser into fire function:

local function fire(event)
    local laser=display.newImageRect("laser.png",75,25) -- always declare objects as locals
    laser.x=spaceship.contentWidth+spaceship.x/2+3
    laser.y=spaceship.y 

    local function removeLaser(target)  -- `onComplete` sends object as a parameter
        target:removeSelf()
        target = nil
    end

    transition.to(laser,{time=1000,x=display.contentWidth, onComplete = removeLaser})
end