[Resolved] Remove bullets after x seconds?

Is there a way to remove object created on the fly (like bullet for example) after specific amount of time?
I’ve tried to use timers, transitions but it looks like it is not possible to use them within dynamically created objects.

Thank you in advance
[import]uid: 101952 topic_id: 24347 reply_id: 324347[/import]

Of course you can. Put up a running piece of offending code and I’ll help you with it! :slight_smile: [import]uid: 21331 topic_id: 24347 reply_id: 98374[/import]

This is my favorite method (very simple) for passing “variables” along with a timer (in this case, the internal ID of the object you created on the fly, so you can delete it when the timer fires).

local function deleteBullet( event )  
 local thisTimer = event.source --"event.source" is the timer ID  
 local thisBullet = thisTimer.objectID --objectID is the bullet ID  
 --the above 2 lines could be simplified to "local thisBullet = event.source.objectID"  
 display.remove( thisBullet )  
 --any other removal tasks here, i.e. if you placed this bullet in another holding table, remove it!  
 --also, if for some reason the bullet has a listener applied, remove that too!  
 thisBullet = nil  
end  
  
local bullet = --your display object, created on the fly  
local t = timer.performWithDelay( 3000, deleteBullet ) --"deleteBullet" is the destination function  
t.objectID = bullet --"attach" the bullet ID to this timer as "objectID"  

That should do it! Timer fires, bullet goes bye-bye. :slight_smile:

Brent
[import]uid: 9747 topic_id: 24347 reply_id: 98414[/import]

@TheRealTonyK

Here is the code:

[lua]physics = require( “physics” )
physics.start()
physics.setGravity(0 , 9.8)

local cannon = display.newRect( 0, _H-75, 40, 60 )

local function shoot (event)
local ball = display.newCircle( cannon.x, cannon.y, 20 )
ball:addEventListener(“collision”, ball)

physics.addBody( ball, “dynamic”, { density=1, friction=0, bounce=0.2 })

function ball:collision (event)
if event.other.hit == “deleter” then
ball:removeBall()
end
end

function ball:removeBall ()
ball:removeSelf()
end

ball:applyLinearImpulse(( ball.x - event.x) * -0.055, (ball.y - event.y) * -0.08, ball.x, ball.y )

– My idea was to use the following code:
– transition.to( ball, { time=1000, onComplete = ball:removeBall()})
– but it simply doesn’t work

end

Runtime:addEventListener(“tap”, shoot)[/lua] [import]uid: 101952 topic_id: 24347 reply_id: 98486[/import]

@IgnisDesign

HA! It works!
I placed it within my code and it works.
The only thing left is to check it with profiler to see if there is memory leak. That’s minor thing.

I am impressed how it’s concise and functional

Thank you


S [import]uid: 101952 topic_id: 24347 reply_id: 98487[/import]