我不知道如何将由一个简单函数创建的对象放在一个表中,让它们作为单独的身份出现..
例如
local function spawncibo()
nuovoCibo = display.newImage("immagini/cibo/cibo001.png")
end
timer.performWithDelay(1500, spawncibo, -1)
我尝试使用 for 循环来执行此操作,但它不起作用(如果我尝试打印表格,我总是得到 nil 结果)。
任何建议将不胜感激!
你可以试试这个...
local spawned = {} -- local table to hold all the spawned images
local timerHandle = nil -- local handle for the timer. It can later be used to cancel it if you want to
local function spawnCibo()
local nuovoCibo = display.newImage('immagini/cibo/cibo001.png')
table.insert(spawned, nuovoCibo) -- insert the new DisplayObject (neovoCibo) at the end of the spawned table.
end
local function frameListener()
for k, v in pairs(spawned) do -- iterate through all key, value pairs in the table
if (conditions) then -- you will probably want to change conditions to some sort of method to determine if you want to delete the cibo
display.remove(spawned[k]) -- remove the part of the object that gets rendered
spawned[k] = nil -- remove the reference to the object in the table, freeing it up for garbage collection
end
end
end
timer.performWithDelay(1500, spawnCibo, 0) -- call spawnCibo() every 1.5 seconds, forever (That's what the 0 is for) or until timer.cancel is called on timerHandle
Runtime:addEventListener('enterFrame', frameListener) --
如果您还有其他问题,请随时提出。
local spawnedCibos = {}
local function spawncibo()
nuovoCibo = display.newImage("immagini/cibo/cibo001.png")
table.insert(spawnedCibos, nuovoCibo);
end
timer.performWithDelay(1500, spawncibo, -1);
local function enterFrameListener( event )
for index=#spawnedCibos, 1, -1 do
local cibo = spawnedCibos[index];
cibo.x = cibo.x + 1;
if cibo.x > display.contentWidth then
cibo:removeSelf();
table.remove(spawnedCibos, index);
end
end
end
如果我正确理解了你的问题,你可以尝试这样的事情:
local cibo = {}
local function spawncibo()
cibo[#cibo+1] = display.newImage(string.format(
"immagini/cibo/cibo%3d.png", #cibo+1))
end
timer.performWithDelay(1500, spawncibo, -1)
这将每 1.5 秒读取文件cibo001.png
, cibo002.png
, ... 并将所有图像放入cibo
数组中。