0

我有一个创建宇宙飞船的类,我希望它包含一个函数,如果它撞到特定的墙壁,它会使飞船自行移除。但是,运行下面的代码,我收到以下错误:

...xenosShip.lua:16:
attempt to index global 'self' (a nil value)
stack traceback:
[C]:?
...xenosShip.lua:16: in function ...xenosShip.lua:14> ?:in function <?:218

>

我错过了什么?

local xenosShip = {}

-- XENOS SHIP COLLISION
local function xenosColl(event)
    if (event.phase == "began" and event.other.myName == "bottomWall") then
    self:removeSelf()
    end
end


-- XENOS SHIP
function xenosShip.new()

    local newXenosShip=display.newSprite( alShipSheet, alShipSeqData )
    newXenosShip:play()
    newXenosShip.x=300
    newXenosShip.y=70
    newXenosShip.myName = "newXenosShip"
    physics.addBody(newXenosShip,"dynamic", {density = 1.0, friction = 0.3, bounce = 1})
    newXenosShip:applyForce(50,2500,newXenosShip.x,newXenosShip.y)
    newXenosShip:addEventListener("collision", xenosColl)

end

return xenosShip
4

2 回答 2

1

您可以这样做,它self不是显示对象,或者它没有对显示对象的引用,因此出现错误object:removeSelf()

local function xenosColl(event)
    if (event.phase == "began" and event.other.myName == "bottomWall") then
        event.target:removeSelf()
    end
end

如果你想使用self你可以这样做。所以 self 现在指的是newXenosShip.

function xenosShip.new()

    local newXenosShip=display.newSprite( alShipSheet, alShipSeqData )
    newXenosShip:play()
    newXenosShip.x=300
    newXenosShip.y=70
    newXenosShip.myName = "newXenosShip"
    physics.addBody(newXenosShip,"dynamic", {density = 1.0, friction = 0.3, bounce = 1})
    newXenosShip:applyForce(50,2500,newXenosShip.x,newXenosShip.y)
    newXenosShip.collision = function(self,event)
        if (event.phase == "began" and event.other.myName == "bottomWall") then
                self:removeSelf()
        end
    end

    newXenosShip:addEventListener("collision")
end
于 2013-07-09T16:41:33.367 回答
0

我最近遇到了同样的错误信息;对我来说,这是一个简单的语法错误,而不是

 playerInstance:resetTargetPosition()

我用过

 playerInstance.resetTargetPosition()

(注意,.而不是:

于 2014-05-07T21:02:55.647 回答