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:

[lua]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);[/lua]

Also, I have read it’s not a good idea to use _G like this - so what is a better alternative?

Thanks!

Tom [import]uid: 55068 topic_id: 14166 reply_id: 314166[/import]

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.
[import]uid: 19626 topic_id: 14166 reply_id: 52117[/import]

Thanks Rob,

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

[lua]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);[/lua]

That appears to work but not sure

Thanks

Tom [import]uid: 55068 topic_id: 14166 reply_id: 52118[/import]