尝试在 'y' 字段上执行算术运算(一个空值)

我是新手,在 Corona 中遇到了这个错误,当游戏结束(lives=0)并且我试图移除背景(使用函数“move”移动背景)时出错:

“尝试在 'y' 字段上执行算术运算(一个空值)” 在第“background.y = background.y + 4”行

有人可以解释一下这是什么错误吗?

代码:

--添加物理

local physics = require("physics")
physics.start()
physics.setGravity(0,0)

local lives = 1
local died = false

--###

--添加背景

background = display.newImageRect("background.png",800,1400)
background.x = display.contentCenterX
background.y = 730
background.myName = "background"

--添加瓶子

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"

--移动函数

local function move()
 bottiglia.y = bottiglia.y + 4
 background.y = background.y + 4
end

Runtime:addEventListener("enterFrame",move)

--###

--添加玩家

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"

--###

--碰撞函数

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 = lives - 1
livesText.text = "生命值: " .. 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,200,80,native.systemFont,36)

--感谢大家

点赞
用户7026995
用户7026995

Runtime 监听器(move函数)一直在工作。它改变了 bottigliabackground 对象的位置,但由于 background 已经不存在了,因此您会收到一个错误。

一个简单的解决方案是在删除 background 对象之前使用 Runtime:[removeEventListener()](https://docs.coronalabs.com/api/type/EventDispatcher/removeEventListener.html)移除全局监听器。

使用 Runtime:removeEventListener(“enterFrame”,move)

2018-02-04 22:00:22
用户9369297
用户9369297

如果你不想移除监听器,你可以添加 nil 检查:

-- 移动函数
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 和 background 是相当危险的。

如果将它们设置为如下,就更加安全:

myGlobalsVars = { }
myGlobalsVars.myGlobalsVars = display.newGroup()
myGlobalsVars.background = display.newGroup()
2018-03-02 08:25:02