My ball function is inside my spawnball function because I have the code for ball creation in another .lua file called gameBall.lua. Here is the code for that followed by the code with the auto removal.
[lua]module(…, package.seeall);
function new()
local img;
local imgWidth;
local imgHeight;
local imgType = math.random(1,3)
if(imgType == 1) then
– Get small ball image
img = “images/sm_ball.png”;
imgWidth = 40; imgHeight = 40;
elseif(imgType == 2) then
– Get medium ball image
img = “images/med_ball.png”;
imgWidth = 60; imgHeight = 60;
elseif(imgType == 3) then
– Get large ball image
img = “images/lrg_ball.png”;
imgWidth = 80; imgHeight = 80;
end
local ball = display.newImageRect(img, imgWidth, imgHeight);
ball:setReferencePoint(display.TopLeftReferencePoint);
while ball.x <= 20 or ball.y >= display.contentHeight - 20 do
ball.x = math.random(0, _W - ball.width); ball.y = math.random(40, _H - ball.height);
end
–ball.alpha = 0;
–transition.to( ball, { alpha=1, time= 250 })
return ball;
end[/lua]
[lua] function spawnBall()
i = i + 1;
ball[i] = gameBall.new();
ball[i].life = 1;
function ball:touch(e)
– If the game is paused, don’t allow balls to be clicked
if (p == true) then
return true;
elseif (e.phase == “ended”) then
e.target.life = e.target.life - 1;
– Play burst sound
audio.play(burst);
– Remove ball and increase score
if (e.target.life == 0) then
e.target:removeSelf();
e.target = nil;
increaseScore();
end
end
return true;
end
ball[i]:addEventListener(“touch”, ball);
local function removeBall()
ball[i]:removeSelf();
decreaseScore();
end
ball[i].tmr = timer.performWithDelay(2000, removeBall, 1);
end
local gameTimer = timer.performWithDelay (spawnSpeed, spawnBall, totalBalls);[/lua] [import]uid: 151658 topic_id: 29135 reply_id: 120056[/import]