一定时间后删除图片。

我创建了一场场景,地面和手榴弹接触时会发生爆炸,玩家总共有5颗手榴弹可用。问题在于,当投掷多颗手榴弹时,只有最新的手榴弹调用了removeSelf函数,而前面的手榴弹没有立即被炸毁和移除。

如果事件.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)
点赞
用户3585949
用户3585949

你声明了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)
2014-05-05 14:33:51