Corona 运行错误:"试图调用一个空值"

下面的代码来自创建并返回一个外星飞船的类,在太空射击游戏的 main.lua 中。

我需要包括一个函数,确定如果该飞船撞击到物体会发生什么,但是当我运行代码并且外星飞船撞击某物时,我会得到 Corona 运行时错误:

试图调用空值 - 开始追溯:[C]:?

-- 碰撞函数
local function xenosColl(event)
    if (event.phase == "began") then
    print("hahf")
    end
end

-- 外星飞船
function xenosShip.new()

    local newXenosShip=display.newSprite( alShipSheet, alShipSeqData )
    newXenosShip:play()
    newXenosShip.x=580
    newXenosShip.y=70
    newXenosShipShape = {0,-40 , 60,0 , 0,40 , -60,0}
    newXenosShip.myName = "newXenosShip"
    physics.addBody(newXenosShip,"dynamic", {density = 1.0, friction = 0.3, bounce = 1, shape = newXenosShipShape})
    newXenosShip:applyForce(0,2000,newXenosShip.x,newXenosShip.y)

    newXenosShip:addEventListener("collision", xenosColl)

    return setmetatable(newXenosShip, xenosShip_mt)

end

return xenosShip

如果我删除了碰撞事件监听器,就不会出现错误,外星飞船会撞到其他物体,所以肯定是在尝试调用函数方面有问题,但我无法找出问题所在。

点赞
用户1682268
用户1682268

我像你一样创建了相同的对象,当我添加 return setmetatable(newXenosShip, xenosShip_mt) 时出现错误,我认为使用 setmetatable 导致对象变为 nil。请尝试删除 metatable。

2013-07-08 21:32:56