How can I make objects disappear after a certain amount of time?

current code (doesn't work - only removes latest):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function platform(event)
        if event.phase == "ended" then
        platforms = display.newImage("platform.png", event.x-120,event.y-20)
        platforms.alpha = 1
        platforms.time = score
        physics.addBody(platforms[i], "kinematic", {bounce = 0.8, density = 5})
        end
end
 
function checkplatforms()
        if platforms.time + 5 < score then
        platforms:removeSelf()
        end
end

use timer.performWithDelay for timed calls for functions
for removing platforms-store them to table and then remove from it when needed

Let me try to explain what is happening. A marker board would be very useful....

When you do a:

someobject = display.newImage(....)

call, that process is allocating a big chunk of memory and storing a reference to it in "someobject".

If your platform() function run again before you take steps to free up that memory (calling someobhect;removeSelf()) then its going to allocate a new object's worth of memory and store its reference in "someobject". The original reference is lost and that memory hangs around until your program exits. This is called a memory leak.

For for fun, lets say that platform() runs 5 times, creating 5 of your platform objects. Four are lost, but are still interacting with the device, you can no longer reference the first 4 because the variable is now referencing the last one created.

This is why when the checkplatform() function runs, it just removes the last one. If this continues over time, your program will bog down and eventually crash.

If you are creating multiple objects of the same type, you have to store them in an array/table so that you can continue to reference them and remove them when done.

views:1415 update:2011/10/4 17:12:07
corona forums © 2003-2011