Search code examples
androidiosluacoronasdk

How to delete a clone when touched


I am working on a program that will create a bunch of clones, and it will delete a clone when the clone is taped on. I only want it to delete the clone that is taped on. I am having an issue with the touch event listener. It says that I am trying to index a nil variable, but I defined it earlier in the program.

I have tried changing the variable to be a global variable.

display.setDefault("background", 0, 0, 200)
math.randomseed(os.time())

local boat = display.newImage( "boatt.png" )
boat.x = 163
boat.y = 225

local score = 0
local spawnCnt = 0
local spawnTable = {}
local startTime = os.time()
local startTime2 = os.time()
local fish_tapped


local function spawn ()
    local obj = display.newImageRect("fishpic.png",70,70)
    obj.x = math.random(1, 300)
    obj.y = (0 - math.random(30, 400))
    obj.isDone = false
    -- Note: Second argument is function name without brakets
    obj:addEventListener("touch", touched()) --i added brackets to this
    return obj
end

local function onSpawn ()
spawnCnt = spawnCnt + 1
spawnTable[spawnCnt] = spawn()
end

local function movement (event)
-- SPAWN OBJECT USING TIMER
if os.time() - startTime >= 1 then 
onSpawn()
startTime = os.time()
end



-- MOVE OBJECT
if spawnCnt > 0 then
for i = 1, spawnCnt do 
if spawnTable[i].isDone == false then 
if spawnTable[i].y > 600 or spawnTable[i].fish_tapped == true then
spawnTable[i].y = 700
spawnTable[i].isDone = true
display.remove(self)
self = nil
else 
spawnTable[i].y = spawnTable[i].y + 4
end
end
end
end 
end

Runtime:addEventListener ("enterFrame",movement)



--when i tried to have touched() in the event listener for touch it said that i was calling a 
--nill value, so I made the funciton global. 
function touched( event )
    local obj = event.target
    obj.fish_tapped = true
end

Solution

  • Try (not tested)

    local function movement (event)
      ...
      -- Replace 
      -- if spawnTable[i].y > 600 or fish_tapped == true then
      -- with
      if spawnTable[i].y > 600 or spawnTable[i].fish_tapped == true then
      ...
    end
    
    local function touched( event )
        local obj = event.target
        obj.fish_tapped = true
    end
    
    local function spawn ()
        local obj = display.newImageRect("fishpic.png",70,70)
        obj.x = math.random(1, 300)
        obj.y = (0 - math.random(30, 400))
        obj.isDone = false
        -- Note: Second argument is function name without brakets
        obj:addEventListener("touch", touched) 
        return obj
    end
    

    Read more: