Hey guys,
Basically what I want to do is spawn an object off screen on the left side and have it scrolled to the right. The player then tries to touch them to break them before they reach the end.
So…I can do all that. I’m getting a problem when they reach the end and I want them removed.
I can also do that if the user DOESN’T touch any of them along the way.
I read this article and it helped me understand how to spawn them http://blog.anscamobile.com/2011/09/how-to-spawn-objects-—-the-right-way/
But he didn’t go over the right way to remove them.
But here’s my code for the spawner:
[lua]local imageTable = {“asteroidsmall.png”,“asteroid02.png”, “asteroid03.png”, “asteroid01.png”};
local AsteroidTable = {};
local function createAsteroid()
local a = mRandom(1,4);
local asteroid = display.newImage(imageTable[a]);
asteroid.x = -cWidth + 50;
asteroid.y = mRandom(20, cHeight - 20)
physics.addBody(asteroid, “kinematic”, {density = 0, friction = 0, bounce = 0});
AsteroidTable[#AsteroidTable + 1] = asteroid;
asteroidGroup:insert(asteroid);
asteroid:setLinearVelocity(200, 0);
function touched (e)
if e.phase == “began” then
table.remove(AsteroidTable, asteroid.index)
asteroid:removeSelf();
asteroid = nil
print(“Astroid got clicked!”)
end
end
asteroid:addEventListener(“touch”, touched);
–
print (#AsteroidTable);
return asteroid;
end
timer.performWithDelay(1000, createAsteroid, 4);[/lua]
So that code works by itself. And the following code works by itself if the user doesn’t click more than 1 asteroid:
[lua]local function removeAsteroid()
if(#AsteroidTable >= 1) then
for i=#AsteroidTable, #AsteroidTable, -1 do
if AsteroidTable[i].x > cWidth then
AsteroidTable[i]:removeSelf();
AsteroidTable[i] = nil;
table.remove(AsteroidTable, i);
end
end
end
end
Runtime:addEventListener(“enterFrame”, removeAsteroid);[/lua]
If the user clicks more than 1 asteroid I get this error:
lua:89: attempt to compare number with nill
Which equals line 7 from the above code.
So if I watch them all leave the screen then they all get removed when the last one goes by, so that part works on it’s own.
It’s when I try to get rid of them by touching them before they get to the end that it seems to mess up the table.
I feel like it might be something really easy, but I’ve been struggling with this for the past few days and I’m not experienced at all. Most of this code is from googling how to do this and seeing other examples here in the forums.
Any help with this would be greatly appreciated and you might also help me get rid of my headache!
[import]uid: 123298 topic_id: 23425 reply_id: 323425[/import]