Question

How to make this spawn 'math.random(1,3)' smile.png every 10 seconds , and delete the smile.png after the left screen

<code>
local physics = require ("physics");
physics.start();

local function listener(me)
 transition.to (me, {time = math.random(1000,4000), x = math.random(10,310), y = -30, onComplete = function()listener(me)end});
end

--Spawning multiple objects in randoms locations
local function spawnsmile()

        local smile = display.newImageRect("smile.png", 45, 45);
        smile:setReferencePoint(display.CenterReferencePoint);
        smile.x = math.random(-10, 400);
        smile.y = -40;
        transition.to( smile, {time = math.random(2000, 8000), x = math.random(-10, 400) , y = 600,});
        physics.addBody(smile, "dynamic", {density = 0.1, bounce = 0.1, friction = .1, radius = 0});

                --Adding touch event
                smile:addEventListener("touch", smile);
end
 tmr = timer.performWithDelay(0, spawnsmile, total_smiles);
<code>

Regards Kevin

Was it helpful?

Solution

Your code was missing total_smiles value assignment and delay argument.

Working code:

local physics = require ("physics");
physics.start();

local function listener(me)
    transition.to (me, {time = math.random(1000,4000), x = math.random(10,310), y = -30, onComplete = function()listener(me)end});
end

--Spawning multiple objects in randoms locations
local function spawnsmile()
    local smile = display.newImageRect("Button.png", 45, 45);
    smile:setReferencePoint(display.CenterReferencePoint);
    smile.x = math.random(-10, 400);
    smile.y = -40;
    transition.to( smile, {time = math.random(2000, 8000), x = math.random(-10, 400) , y = 600,});
    physics.addBody(smile, "dynamic", {density = 0.1, bounce = 0.1, friction = .1, radius = 0});

    --Adding touch event
    smile:addEventListener("touch", smile);
end

local total_smiles = 15
tmr = timer.performWithDelay(10000, spawnsmile, total_smiles);

Moreover, you should store references to created smiles in order to properly destroy them and don't leak memory. more info on memory managment

local smiles = {}
table.insert(smiles, smile)

And disposal:

for i=#smiles,1,-1 do
   smiles[i]:removeSelf()
   smiles[i] = nil
end

OTHER TIPS

change your timer to perform every 10.000 ms instead of 0. And your listener function doesnt really fill any purpose, remove that and change your transition.to inside of spawnsmile function to

    transition.to( smile, {time = math.random(2000, 8000), x = math.random(-10, 400) , y = 600, onComplete = function(obj) obj:removeSelf() obj = nil end});

That should do what you want it to do =) Also there needs to be a value inside total_smiles, but i guess you have it elsewhere.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top