尝试对字段'y'执行算术(零值)

问题描述 投票:2回答:2

我是新来的,我在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 )

- 谢谢你们

lua corona
2个回答
1
投票

运行时监听器(move函数)一直在​​工作。它改变了bottigliabackground对象的位置,但由于background不再存在,你会得到一个错误。

一个简单的解决方案是在删除removeEventListener()对象之前使用Runtime:background删除全局侦听器。

使用Runtime:removeEventListener("enterFrame", move)


0
投票

如果您不想删除侦听器,可以添加对nil的检查:

--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

使用这样的全局变量也很危险:bottiglia和背景。

如果将它们作为(或类似的东西),你可以使它更安全:

myGlobalsVars = { }
myGlobalsVars.myGlobalsVars = display.newGroup()
myGlobalsVars.background = display.newGroup()
© www.soinside.com 2019 - 2024. All rights reserved.