在触摸时销毁生成的对象 Corona SDK

Destroy spawned objects on touch Corona SDK

我想通过触摸屏幕上每 1 秒随机生成的对象来销毁它们。 我写了一些东西,但它只破坏了第一个生成的对象。 我对这件事很菜鸟,有人可以帮助我吗? 我写了这段代码:(雷声是我的对象)

local thunder = display.newImageRect( "thunder_icon.png",100,100)
thunder.x = larghezza / 2
thunder.y = altezza / 2
local spawnTimer

local function myToccoListener(event)
    display.remove(thunder)
    return true
end

local spawn = function()
    local xCoord = math.random(display.contentWidth * 0, display.contentWidth * 1.0)
    local thunder = display.newImageRect( "thunder_icon.png",100,100)
    thunder.x = xCoord
    thunder.y = 50
    thunder:addEventListener("touch", myToccoListener)
end
spawnTimer = timer.performWithDelay(1000, spawn, -1)

我用这个解决了我的问题:

local spawnTimer

local spawn = function()
    local xCoord = math.random(display.contentWidth * 0, display.contentWidth * 1.0)
    local thunder = display.newImageRect( "thunder_icon.png",100,100)
    thunder.x = xCoord
    thunder.y = 50
    local function myToccoListener(event)
    display.remove(thunder)
    return true
    end
    thunder:addEventListener("touch", myToccoListener)
end

spawnTimer = timer.performWithDelay(1000, spawn, -1)

无论您的代码是否正确,只需进行一次修改即可。

 local thunder = display.newImageRect( "thunder_icon.png",100,100)
 thunder.x = larghezza / 2
  thunder.y = altezza / 2
 local spawnTimer

local function myToccoListener(event)
   -- display.remove(thunder)
    if event.target then 
       event.target:removeSelf()
       return true
    end 
end

local spawn = function()
   local xCoord = math.random(display.contentWidth * 0, display.contentWidth * 1.0)
  local thunder = display.newImageRect( "thunder_icon.png",100,100)
  thunder.x = xCoord
  thunder.y = 50
  thunder:addEventListener("touch", myToccoListener)
end
spawnTimer = timer.performWithDelay(1000, spawn, -1)