如何每隔10秒生成一次'math.random(1,3)'smile.png,并在左侧屏幕后删除smile.png
<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>
问候凯文
答案 0 :(得分:2)
您的代码缺少total_smiles值分配和延迟参数。
工作代码:
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);
此外,您应该存储对创建的微笑的引用,以便正确销毁它们并且不会泄漏内存。 more info on memory managment
local smiles = {}
table.insert(smiles, smile)
处置:
for i=#smiles,1,-1 do
smiles[i]:removeSelf()
smiles[i] = nil
end
答案 1 :(得分:0)
更改您的计时器以执行每10.000毫秒而不是0.并且您的侦听器功能并没有真正填满任何目的,删除它并将您的transition.to更改为spawnsmile函数内部
transition.to( smile, {time = math.random(2000, 8000), x = math.random(-10, 400) , y = 600, onComplete = function(obj) obj:removeSelf() obj = nil end});
那应该做你想做的事情=)同样需要在total_smiles中有一个值,但我想你已经在其他地方了。