我正在开发一个程序,该程序将创建一堆克隆,并且在克隆克隆后将其删除。我只希望它删除粘贴在磁带上的克隆。我在触摸事件监听器上遇到了问题。它说我正在尝试索引一个nil变量,但是我在程序的前面定义了它。
我尝试将变量更改为全局变量。
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
答案 0 :(得分:0)
尝试(未测试)
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
了解更多: