How can I tell all my enemies to die when, for example, I click on a particular button?
Well… it depends how you set your enemies up.
If you have a central list of enemies which is updated when an enemy is created or destroyed then you can iterate through that and delete everything on command.
The other way is to use a messaging system - a bit like event listeners - that your enemies listen to, and broadcast a ‘die now’ message.
You could, perhaps, put them all in a group which doesn’t itself move and move them within the group, so the group acts like a container, but I haven’t tried this, can’t see why it wouldn’t work.
The listener method is ideally what I need. However the scope of the functions seems to be a problem since I cant pass instructiong such as die() or move() from outside the object scope. Is there a way for me to do this without saving a reference to each object in the scene? (eg. when there are a random # of objects created) see code below
[lua]
local now = false
local function nowTrue(event)
if event.phase == “ended” then
now = true
end
end
for i = 1,math.random(1,10) do
local rect = display.newRect( 25 * i, 100, 20, 20 )
local function move(event)
if event.phase == “ended” and now then
transition.to(rect, {y=100 +30 * i})
end
end
Runtime:addEventListener ( “touch”, move )
end
local moveButton = display.newText( “Move”, 160, 500, Helvetica, 14 )
moveButton:addEventListener ( “touch”, nowTrue )
[/lua]
Well… it depends how you set your enemies up.
If you have a central list of enemies which is updated when an enemy is created or destroyed then you can iterate through that and delete everything on command.
The other way is to use a messaging system - a bit like event listeners - that your enemies listen to, and broadcast a ‘die now’ message.
You could, perhaps, put them all in a group which doesn’t itself move and move them within the group, so the group acts like a container, but I haven’t tried this, can’t see why it wouldn’t work.
The listener method is ideally what I need. However the scope of the functions seems to be a problem since I cant pass instructiong such as die() or move() from outside the object scope. Is there a way for me to do this without saving a reference to each object in the scene? (eg. when there are a random # of objects created) see code below
[lua]
local now = false
local function nowTrue(event)
if event.phase == “ended” then
now = true
end
end
for i = 1,math.random(1,10) do
local rect = display.newRect( 25 * i, 100, 20, 20 )
local function move(event)
if event.phase == “ended” and now then
transition.to(rect, {y=100 +30 * i})
end
end
Runtime:addEventListener ( “touch”, move )
end
local moveButton = display.newText( “Move”, 160, 500, Helvetica, 14 )
moveButton:addEventListener ( “touch”, nowTrue )
[/lua]