Removing object in group that do not meet a condition

Hey all,

I’m making a game that uses randomly generated objects, where a new one is spawned once one is used. However, since you can skip over objects by taking a different path, I also want to remove them once they go offscreen so I don’t run out if I skip too many. Here’s the code I have right now:

[lua]for m,mN in ipairs(nodes) do
if mN.x < -game.x then --game.x is a negative value which shifts all game objects to the left
–this tests to see if objects have shifted offscreen
nodes:remove(m) --nodes is the group of objects
newRandomNode(lData[levNum]) --makes a new object
end
end[/lua]

And yes, before you ask, I tried seeing if x < 0, but the x-value of the objects remains constant, it’s just the game group (or you can think of it as the camera) that shifts.

Thanks in advance. [import]uid: 16445 topic_id: 11639 reply_id: 311639[/import]

In my games I have a sprites table and each sprite is an object which also holds the physics body (where needed). Each sprite has a property self.doDieOutsideField = true, which – if kept at its default true – does something along the lines of

function self:dieOutsideField()  
 if self.doDieOutsideField then  
 if self:isOutside() then self.gone = true end  
 end  
end  
  
function self:isOutside()  
 return (self.x + self.width \< app.minX) or  
 (self.x - self.width \> app.maxX) or  
 (self.y + self.height \< app.minY) or  
 (self.y - self.height \> app.maxY)  
end  

… which in turn becomes meaningful once the main handler loop is accessed (once per frame) as it includes a call to the following function …

function appHandleRemovals()  
 for id, sprite in pairs(app.sprites) do  
 if sprite ~= nil and (sprite.energy \<= 0 or sprite.gone) then  
 if sprite.handleWhenGone ~= nil then sprite:handleWhenGone() end  
 if app.sprites[id].removeSelf then app.sprites[id]:removeSelf() end  
 app.sprites[id] = nil  
 end  
 end  
end  

(For illustration purposes here I’ve removed some checks and functionality that were dealing with removing children before its parent, handling special groups during a paused game, as well as handling default disappearance effects.)

Note above also calls an optional handleWhenGone() function of the sprite object, which can be used to trigger explosions etc.

Hope this helps a bit. [import]uid: 10284 topic_id: 11639 reply_id: 42641[/import]