2013-07-09 77 views
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 

回答

1

你能做到這樣的,self不是顯示對象,也沒有引用顯示對象,所以如果你想使用自我有一個在object:removeSelf()

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

錯誤你可以這樣做。所以自我現在指的是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 
+0

輝煌,謝謝!請問我爲什麼新XenosShip似乎是事件的目標,而不是在這種情況下的自我?我之前在代碼中使用過相同的構造,雖然不是在一個類中,它在那裏工作得很好。 – Ravn

+0

它取決於您如何將顯示對象引用到類的類。對不起,我不能很好地解釋它,我在科羅納和盧阿還是個新手。 – NaviRamyle

0

我最近遇到了同樣的錯誤信息;對我來說,這是一個簡單的語法錯誤,而不是

playerInstance:resetTargetPosition() 

我用了

playerInstance.resetTargetPosition() 

(注意.而不是:

相關問題