一段时间后删除图像

时间:2014-05-05 13:55:27

标签: timer lua listener collision-detection corona

我创造了一个手榴弹和地面接触爆炸的场景,玩家总共可以使用5枚手榴弹。问题是当不止一枚手榴弹被抛出时,自动功能只需要最新的手榴弹和之前的手榴弹没有被吹走并立即被移除。

 if event.object1.myname=="ground" and event.object2.myname=="grenade2" then
 local ex2=audio.play(bomb,{loops=0})
 health1=health1-1
 check()
 health1_animation:setFrame(health1)
 explosion_animation2=display.newSprite(explosion_sheet,explosion_sequence)
 explosion_animation2.x=event.object2.x
 explosion_animation2.y=event.object2.y
 explosion_animation2:play() 
 end
 timer.performWithDelay(300,function() explosion_animation2:removeSelf()
 end,1)

1 个答案:

答案 0 :(得分:1)

您将explosion_animation2声明为全局变量,因此每次调用此冲突代码时都会覆盖它。你需要将explosion_animation2作为局部变量,以便在延迟函数中使用它将在它周围创建一个闭包:

local explosion_animation2
if event.object1.myname=="ground" and event.object2.myname=="grenade2" then
    local ex2=audio.play(bomb,{loops=0})
    health1=health1-1
    check()
    health1_animation:setFrame(health1)
    explosion_animation2=display.newSprite(explosion_sheet,explosion_sequence)
    explosion_animation2.x=event.object2.x
    explosion_animation2.y=event.object2.y
    explosion_animation2:play() 
end
timer.performWithDelay(300,function() explosion_animation2:removeSelf()
end,1)

如果由于某种原因你依赖于explosion_animation2是全局的,你可以改为制作本地副本:

if event.object1.myname=="ground" and event.object2.myname=="grenade2" then
    local ex2=audio.play(bomb,{loops=0})
    health1=health1-1
    check()
    health1_animation:setFrame(health1)
    explosion_animation2=display.newSprite(explosion_sheet,explosion_sequence)
    explosion_animation2.x=event.object2.x
    explosion_animation2.y=event.object2.y
    explosion_animation2:play() 
end
local closure_var=explosion_animation2
timer.performWithDelay(300,function() closure_var:removeSelf()
end,1)