事件监听器的 Corona Sdk 问题
Coronasdk Issue with addeventListeners
最近我在编写一个新游戏时 运行 遇到了一个我似乎无法解决的问题。
这是代码:
function newPower()
rand = math.random( 100 )
if (rand < 80) then
powerup = display.newImage("power.png");
powerup.class = "powerup"
powerup.x = 60 + math.random( 160 )
powerup.y = -100
physics.addBody( powerup, { density=0.9, friction=0.3, bounce=0.3} )
powerup:addEventListener( "touch", handlePowerTouch )
end
end
local function handlePowerTouch( event )
if event.phase == "began" then
currentScore = currentScore * 2
currentScoreDisplay.text = string.format( "%06d", currentScore )
event.target:removeSelf()
return true
end
end
local function spawnpowers()
-- Spawn a new powerup every second until canceled.
spawnPower = timer.performWithDelay( 1000, newPower, -1 )
end
如果能帮助解决这个问题,我们将不胜感激!
我遇到的问题是当我单击 "run" 或 "play" 时游戏开始运行然后崩溃并显示此消息:
addEventListener:侦听器不能为 nil:nil 堆栈回溯:
?: 在函数中 'addeventListener'
game.lua63: 在函数'_listener' <-- 我已经在上面给了你 game.lua:63。
谢谢
powerup:addEventListener( "touch", handlePowerTouch )
这里 handlePowerTouch 是 nil,因为函数定义跟在这一行之后。
将您的函数定义移到该行的前面,然后它应该可以工作。
顺便说一句,你有这么多全局变量有什么原因吗?您应该尽可能使用局部变量。
最近我在编写一个新游戏时 运行 遇到了一个我似乎无法解决的问题。
这是代码:
function newPower()
rand = math.random( 100 )
if (rand < 80) then
powerup = display.newImage("power.png");
powerup.class = "powerup"
powerup.x = 60 + math.random( 160 )
powerup.y = -100
physics.addBody( powerup, { density=0.9, friction=0.3, bounce=0.3} )
powerup:addEventListener( "touch", handlePowerTouch )
end
end
local function handlePowerTouch( event )
if event.phase == "began" then
currentScore = currentScore * 2
currentScoreDisplay.text = string.format( "%06d", currentScore )
event.target:removeSelf()
return true
end
end
local function spawnpowers()
-- Spawn a new powerup every second until canceled.
spawnPower = timer.performWithDelay( 1000, newPower, -1 )
end
如果能帮助解决这个问题,我们将不胜感激! 我遇到的问题是当我单击 "run" 或 "play" 时游戏开始运行然后崩溃并显示此消息:
addEventListener:侦听器不能为 nil:nil 堆栈回溯: ?: 在函数中 'addeventListener' game.lua63: 在函数'_listener' <-- 我已经在上面给了你 game.lua:63。
谢谢
powerup:addEventListener( "touch", handlePowerTouch )
这里 handlePowerTouch 是 nil,因为函数定义跟在这一行之后。
将您的函数定义移到该行的前面,然后它应该可以工作。
顺便说一句,你有这么多全局变量有什么原因吗?您应该尽可能使用局部变量。