In my project, I create multiple objects from a single image file. On tap, I want their number to appear on the screen and the objects themselves to disappear. I took the counting function from the lessons. My code so far.
local tapCount = 0 local ballsTable = {} local centerX = display.contentCenterX local centerY = display.contentCenterY local height = display.contentHeight local width = display.contentWidth local background = display.newImageRect( "background.png", 360, 570 ) background.x = centerX background.y = centerY local tapText = display.newText( tapCount, centerX, 20, native.systemFont, 40 ) tapText:setFillColor( 0, 0, 0 ) local function tapCounter() tapCount = tapCount + 1 tapText.text = tapCount end local function getBall(imagePath, x, y) local ball = display.newImageRect("ball.png", 25, 25) ball.x = math.random(height) ball.y = math.random(width) return ball end local function createBalls() for i = 1, 30 do local ball = getBall("ball.png", math.random(height), math.random(width)) table.insert(ballsTable, ball) ball:addEventListener("tap", tapCounter) end end local function setup() math.randomseed(os.time()); createBalls() end setup()
Now I want to create a function that deletes the objects on tap. I found two functions that should do what I need, but I don’t know how to fit them into my project and where I should place the EventListener.
local function deleteBall() for i = #ballsTable, 1, -1 do local thisBall = ballsTable[i] display.remove( thisBall ) table.remove( ballsTable, i ) end end local function removeBall() for i=1,#ballsTable do local v = ballsTable[i] if ( v and v.id == event.target.id ) then table.remove( ballsTable,i ) break end v = nil end end