我是新来的,我在Corona中遇到这个错误,当游戏结束时(生命= 0)我试图移除背景(移动时使用“移动”功能):
“尝试对字段'y'执行算术运算(零值)” 在行中“background.y = background.y + 4”
有没有人可以解释我的错误是什么?
代码:
--add PHYSICS
local physics = require( "physics" )
physics.start()
physics.setGravity( 0, 0 )
local lives = 1
local died = false
--###
--add background
background = display.newImageRect( "background.png", 800, 14000 )
background.x = display.contentCenterX
background.y = 730
background.myName = "background"
--add bottle
bottiglia = display.newImageRect( "bottiglia.png", 41, 104 )
physics.addBody( bottiglia, "dynamic", { radius=45, bounce=0.5 } )
bottiglia.x = display.contentCenterX
bottiglia.y = 10
bottiglia.myName = "bottiglia"
--function move
local function move()
bottiglia.y = bottiglia.y + 4
background.y = background.y + 4
end
Runtime:addEventListener( "enterFrame", move )
--###
--add player
studente = display.newImageRect( "studente.png", 98, 79 )
studente.x = display.contentCenterX
studente.y = display.contentHeight - 100
physics.addBody( studente, { radius=40, isSensor=true } )
studente.myName = "studente"
--###
--function collision
local function onCollision( event )
if ( event.phase == "began" ) then
local obj1 = event.object1
local obj2 = event.object2
if ( ( obj1.myName == "studente" and obj2.myName == "bottiglia" ) or
( obj1.myName == "bottiglia" and obj2.myName == "studente" ) )
then
if ( died == false ) then
died = true
-- lives update
lives = lives - 1
livesText.text = "Lives: " .. lives
if ( lives == 0 ) then
display.remove( studente )
display.remove( background)
timer.performWithDelay( 100, endGame )
end
else
studente.alpha = 0
timer.performWithDelay( 500, restoreStudente )
end
end
end
end
Runtime:addEventListener( "collision", onCollision )
livesText = display.newText( "Lives: " .. lives, 200, 80, native.systemFont, 36 )
- 谢谢大家
答案 0 :(得分:1)
运行时侦听器(std::shared_ptr
函数)一直在运行。它会更改move
和bottiglia
个对象的位置,但由于background
不再存在,因此会出现错误。
一个简单的解决方案是在删除background
对象之前使用Runtime:removeEventListener()删除全局侦听器。
使用background
答案 1 :(得分:0)
如果您不想删除侦听器,可以添加对nil的检查:
BytesIO
使用这样的全局变量也很危险:bottiglia和背景。
如果将它们作为(或类似的东西),你可以使它更安全:
--function move
local function move()
if (bottiglia ~= nil and bottiglia.y ~= nil) then
bottiglia.y = bottiglia.y + 4
end
if (background~= nil and background.y ~= nil) then
background.y = background.y + 4
end
end