Dynamically generating display groups: why doesnt this work?

Hello,

I need to dynamically generate display groups. It should be pretty easy but I'm getting stuck. Here's my code so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
local currentX = 50;
local monsterCounter = 0;
 
local function spawnMonster()
 
local monster = display.newRect(50,50,50,50);
monsterCounter = monsterCounter + 1;
_G["monsterDisplayGroup"..monsterCounter] = display.newGroup();
_G["monsterDisplayGroup"..monsterCounter]:insert(monster);
 
transition.to(_G["monsterDisplayGroup"..monsterCounter], {x=300, time=2000, onComplete = function()
_G["monsterDisplayGroup"..monsterCounter]:removeSelf();
print("removing: ");
print(_G["monsterDisplayGroup"..monsterCounter]);
end});
 
end
 
 
timer.performWithDelay(2000, spawnMonster, 5);

Well to answer the 2nd question first, ideally you would either have a module with methods to get/set/move/remove your monsters and your global space wouldn't need to know about them.

If you're not using Director and have everything in main.lua, it could just be a local variable to your main.lua chunk.

As for why the 2nd one isn't working, I bet its not removing any but the last one?

When you do that enclosure for the onComplete and it fires 2 seconds after, the monster is created, your create event has already spawned and "monsterCount" is 5 (or whatever Max value it will get to) when those call backs start firing.

Thanks Rob,

Can you store the location of a displayGroup in a variable, and then use that to remove it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
local currentX = 50;
local monsterCounter = 0;
 
local function spawnMonster()
 
local monster = display.newRect(50,50,50,50);
monsterCounter = monsterCounter + 1;
_G["monsterDisplayGroup"..monsterCounter] = display.newGroup();
_G["monsterDisplayGroup"..monsterCounter]:insert(monster);
 
monster.displayGroup = _G["monsterDisplayGroup"..monsterCounter];
 
transition.to(_G["monsterDisplayGroup"..monsterCounter], {x=300, time=2000, onComplete = function()
monster.displayGroup:removeSelf();
print("removing: ");
print(monster.displayGroup);
end});
 
end
 
 
timer.performWithDelay(1000, spawnMonster, 5);
views:643 update:2011/9/27 8:54:05
corona forums © 2003-2011