删除所有产生的硬币 [英] 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 )
推荐答案
首先,您需要从显示中删除所有硬币.然后,您将清除coin
表:
First you would remove all coins from the display. Then you would clear the coin
table:
for i=1,#coin do
coin[i]:removeSelf()
end
coin = {} -- forget all coins
假设coin
表是您存储硬币的唯一其他位置,则可以完成此操作.
Assuming coin
table is the only other place you store your coins, this will do it.
请注意,您不能在removeSelf
之后的循环中使用coin[i]=nil
:一旦表上有孔,则#运算符基本上将不可用.您也不能使用table.remove,因为每次我都会增加,所以您会错过项目(尝试,您会看到).对也存在相同的问题:遍历表时无法编辑表.但是,您可以这样做:
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. You can't use table.remove either, because i gets incremented every time, so you'll miss items (try, you'll see). 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 {}
我能想到的是将N个项目设为n个而不是让gc用一个table = {}
语句处理它的唯一原因是,如果您对钱币表有多个引用(我将重命名为钱币表,顺便说一句) (为清楚起见).
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).
这篇关于删除所有产生的硬币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!