Question

I have created a scene where grenade and ground touches explosion occurs,there are total 5 grenades avialable to the player.The problem is when more than one grenade are being thrown removeself function is called for the latest grenade only and the previous one is not blown and removed immediately.

 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)
Was it helpful?

Solution

You are declaring explosion_animation2 as a global variable, and so it is overwritten each time this collision code is called. You'll want to have explosion_animation2 as a local variable so that using it in the delayed function will create a closure around it:

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)

If for some reason you rely on explosion_animation2 being global, you can make a local copy instead:

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top