Corona Sdk - 删除具有相同名称的一个对象实例

时间:2014-07-03 14:42:17

标签: android lua corona

我正在使用Corona Sdk进行太空游戏,我的代码中的一个功能用于激发激光束。这些光束应该在完成过渡时消失,但我有一个问题:当我同时发射多个(使用按钮小部件(每次点击一次))时,只有最后一个发射消失,紧接着第一个一个完成它的过渡。

这是我现在的代码:

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

我应该如何处理function removeLaser(event)

1 个答案:

答案 0 :(得分:0)

只需将removeLaser放入fire函数:

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