OK, so pretty much all the tutorials I’ve read have said that when writing a game it makes sense to add the enemies/bullets/whatever into a table so that they can be easily referenced. However, what I’m stuck on is the best way to remove the entities from the table once they have been killed.
This is the code that I have for the bombs so far…
(A new bomb is generated every three quarters of a second)
(bmbText is just a text field I put in to easily keep track of how many bombs are in the table)
[lua]
local bombs={}
function onLocalCollision(self, event)
if self.name==“bomb” and event.other.name==“ground” then
print (“BANG!!”)
local dead=table.indexOf(bombs, self)
bombs[dead]:removeSelf()
–bombs[dead]=nil
bmbText.text="BOMBS: " … #bombs
end
end
function dropBomb()
local foo=_m(1,#enemies)
local nb= #bombs+1
bombs[nb]=display.newCircle(bullets,0,0,2)
bombs[nb].x=enemies[foo].x; bombs[nb].y=enemies[foo].y
bombs[nb]:setFillColor(0,255,255)
physics.addBody(bombs[nb], “dynamic”, {bounce=0, density=.25})
bombs[nb].name=“bomb”
bombs[nb].collision=onLocalCollision
bombs[nb]:addEventListener(“collision”, bombs[nb])
bmbText.text="BOMBS: " … #bombs
end
[/lua]
As it stands at the moment the bombs drop down and disappear when they hit the ground as they should but they are not being removed from the table correctly as #bombs indicates.
However, if I uncomment the [lua]–bombs[dead]=nil[/lua] line then it seems to work most of the time but every so often one of the bombs is not removed from either the table or the display.
I’m sure my code isn’t very efficient and there’s probably a much better way of doing this so I would be eternally grateful if anyone could point me in the right direction.
Cheers
Chris
[import]uid: 7841 topic_id: 37468 reply_id: 67468[/import]