[英]remove all spawned coins
What is the best way to remove all spawned coins when the game is over? 游戏结束后,删除所有衍生硬币的最佳方法是什么?
Here is the code that spawns the coins: 这是产生硬币的代码:
screenGroup = self.view
coin = {}
coinspawn = function()
i = display.newSprite( imageSheet1, sequenceData1 )
i.x = display.contentWidth
i.y = math.random(0, display.contentHeight-50)
i:play()
i.collided = true
i.name = "coin"
physics.addBody(i, "dynamic",
{density=.1, bounce=0.1, friction=.2, shape= shape2 ,filter=playerCollisionFilter }
)
--player.gravityScale = 0.5
coinIntro = transition.to(i,{time=2500, x=display.contentWidth - display.contentWidth -500 ,onComplete=jetReady , transition=easing.OutExpo } ) --
coin[#coin+1] = i
end
tmrcoin = timer.performWithDelay( 1000, coinspawn, 0 )
First you would remove all coins from the display. 首先,您将从显示屏中删除所有硬币。 Then you would clear the
coin
table: 然后,您将清除
coin
表:
for i=1,#coin do
coin[i]:removeSelf()
end
coin = {} -- forget all coins
Assuming coin
table is the only other place you store your coins, this will do it. 假设
coin
表是您存储硬币的唯一其他地方,那么就可以了。
Note that you can't use coin[i]=nil
in the loop after removeSelf
: as soon as table has holes, the # operator is basically unusable. 请注意,在
removeSelf
之后,您不能在循环中使用coin[i]=nil
:一旦表上有孔,则#运算符基本上将不可用。 You can't use table.remove either, because i gets incremented every time, so you'll miss items (try, you'll see). 您也不能使用table.remove,因为每次我都会增加,所以您会错过项目(尝试,您会看到)。 Same issue with pairs: you can't edit a table while iterating through it.
对同样存在问题:遍历表时无法编辑表。 You could however do this:
但是,您可以这样做:
local numCoins = #coin
for i=1,numCoins do
coin[i]:removeSelf()
coin[i]=nil
end
-- now coin is {}
The only reason I can think of to nil N items instead of letting the gc take care of it with one table = {}
statement is if you have more than one reference to your coin table (which I would rename to coins, BTW, for clarity). 我想到零个项目而不是让gc用一个
table = {}
语句处理它的唯一原因是,如果您对硬币表有多个引用(我将其重命名为硬币,BTW,对于明晰)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.