How to remove object when it goes off screen?

Right now I have this code in my gameLoop(gets called every frame):

[code]
if event.time - timeLastEnemy >= math.random(100, 1000) then
– Randomly position it on the top of the screen
names = {“rock1”,“rock1”,“rock1”,“rock1”,“rock2”,“rock2”,“rock3”,“rock4”,“rock5”,“rock6”,“rock7”}
name = names[math.random(11)]
enemy = display.newImage(name…".png")
halfEnemyWidth = enemy.contentWidth * .5
enemy.x = math.random(halfEnemyWidth, display.contentWidth - halfEnemyWidth)
enemy.y = -enemy.contentHeight

– This has to be dynamic, making it react to gravity, so it will
– fall to the bottom of the screen.
physics.addBody(enemy,physicsData:get(name))
enemy.name = “enemy”

enemiesLayer:insert(enemy)
timeLastEnemy = event.time
end

if enemy.y > 480 then
print(“hiiii”)
enemy:removeSelf()
end

(code stops here)
Then the enemies do not get removed (i know becuz my hiiii message isnt being displayed)
The error is “attempt to index global ‘enemy’(a nil value)”

Please help, Jason [import]uid: 8335 topic_id: 12572 reply_id: 312572[/import]

Hello Jason,

You are gonna have to add either a timer or an Event Listener that will check if the object went of the screen. Depends if you want a more aggressive check (Event Listener will check every frame), or want to control it (timer).
[lua]local function check()
if enemy.y > 480 then
print(“hiiii”)
display.remove( enemy )
enemy = nil
end
end
Runtime:addEventListener(“enterFrame”, check)
–or
–timer.performWithDelay(100, check, 0) [import]uid: 17138 topic_id: 12572 reply_id: 45970[/import]

That didnt work, that was similar to what I had, except there you have to add another event listener. I think it might have something to do with there being multiple objects being called enemy. [import]uid: 8335 topic_id: 12572 reply_id: 45976[/import]

Thats probably why, i’m sure there is away to do it, but i’m not sure how…sorry. [import]uid: 17138 topic_id: 12572 reply_id: 45978[/import]

how about adding lines as screen borders and removing the objects in the collision event of these lines ?

in the collision event u can use…
[lua] otherObject = event.other
otherObject:removeSelf() [/lua]
[import]uid: 71210 topic_id: 12572 reply_id: 45986[/import]

Started corona today.

My solution (object goes off side = appears on other side)

function checkobjects() if melon.x \> display.contentWidth then melon.x = 0 elseif melon.x \< 0 then melon.x = display.contentWidth end end Runtime:addEventListener("enterFrame", checkobjects) [import]uid: 79135 topic_id: 12572 reply_id: 52166[/import]