In my game, I am trying to remove spawned display objects when they fall below the screen (maximumY) by using a for loop, but when I run the code it removes the first couple objects that pass maximumY, then I get a runtime error that says the objects are nil.
Thanks in advance
local bounds, childGroup, spawnTimer
local spawnedObject = {}
local P = {}
local minimumX = 50
local maximumX = display.viewableContentWidth - 50
local minimumY = 50
local maximumY = display.viewableContentHeight - 50
bounds = {
xMin = 0,
xMax = display.viewableContentWidth,
yMin = -300,
yMax = -100,
spawnTime = 500,
spawnOnTimer = 1,
spawnInitial = 0
}
function P.spawnItem()
comet = display.newImageRect( “comet2.png”, 150, 150 )
comet.x = math.random( bounds.xMin, bounds.xMax )
comet.y = math.random( bounds.yMin, bounds.yMax )
comet.myName = “comet”
physics.addBody( comet, { density=1.0, bounce=0.1, radius=70, filter=cometCollisionFilter } )
comet.angularVelocity = -200
comet.gravityScale = 0.8
comet2 = display.newImageRect( “comet3.png”, 130, 130 )
comet2.x = math.random( bounds.xMin, bounds.xMax )
comet2.y = math.random( bounds.yMin, bounds.yMax )
comet2.myName = “comet2”
physics.addBody( comet2, { density=1.0, bounce=0.1, radius=60, filter=comet2CollisionFilter } )
comet2.angularVelocity = 375
comet2.gravityScale = 1.0
comet3 = display.newImageRect( “comet2.png”, 140, 140 )
comet3.x = math.random( bounds.xMin, bounds.xMax )
comet3.y = math.random( bounds.yMin, bounds.yMax )
comet3.myName = “comet3”
physics.addBody( comet3, { density=1.0, bounce=0.1, radius=65, filter=comet3CollisionFilter } )
comet3.angularVelocity = -250
comet3.gravityScale = 0.9
spawnedObject[#spawnedObject+1] = comet
spawnedObject[#spawnedObject+1] = comet2
spawnedObject[#spawnedObject+1] = comet3
for i = 1, #spawnedObject do
if spawnedObject[i].y > maximumY then
spawnedObject[i]:removeSelf()
end
end
childGroup = display.newGroup()
childGroup:insert( comet )
childGroup:insert( comet2 )
childGroup:insert( comet3 )
sceneGroup:insert( childGroup )
end
spawnTimer = timer.performWithDelay( bounds.spawnTime, P.spawnItem, 0 )
I also tried creating a function inside P.spawnItem() over the for loop but had no luck.