2014-02-14 26 views
0

我試圖讓一些碰撞檢測工作,但我似乎無法弄清楚問題是什麼。電暈/ Lua和碰撞:「嘗試連接字段'名稱'(一個零值)」

我得到的錯誤是

...\main.lua:178:attempt to concatenate field 'name' (a nil value)

什麼我是這樣的:我有一個停留在一個固定的X座標一箱(「船」),但上下移動。它意味着要穿過一個由兩個矩形組成的「隧道」,兩個矩形之間有間隙,我試圖檢測船與隧道壁(即矩形)之間的碰撞。

碰撞發生時我得到這個錯誤。我的很多代碼只是官方Corona文檔的修改版本,我無法弄清楚問題所在。

這裏是代碼中的相關部分:

function playGame() 
    -- Display the ship 
    ship = display.newRect(ship); 
    shipLayer:insert(ship); 
    -- Add physics to ship 
    physics.addBody(ship, {density = 3, bounce = 0.3}); 

    ... 

    beginRun(); 
end 

function beginRun() 
    ... 
    spawnTunnel(1100); -- this just calls the createTunnel function at a specific location 
    gameListeners("add"); 
    ... 
end 

function gameListeners(event) 
    if event == "add" then 
     ship.collision = onCollision; 
     ship:addEventListener("collision", ship); 
     -- repeat above two lines for top 
     -- and again for bottom 
    end 
end 

-- Collision handler 
function onCollision(self,event) 
    if (event.phase == "began") then 
     -- line 178 is right below this line ---------------------------------- 
     print(self.name .. ": collision began with " .. event.other.name) 
end 

-- Create a "tunnel" using 2 rectangles 
function createTunnel(center, xLoc) 
    -- Create top and bottom rectangles, both named "box" 
    top = display.newRect(stuff); 
    top.name = "wall"; 
    bottom = display.newRect(stuff); 
    bottom.name = "wall"; 

    -- Add them to the middleLayer group 
    middleLayer:insert(top); 
    middleLayer:insert(bottom); 

    -- Add physics to the rectangles 
    physics.addBody(top, "static", {bounce = 0.3}); 
    physics.addBody(bottom, "static", {bounce = 0.3}); 
end 

我只得到錯誤信息一旦這兩個對象應該發生碰撞,因此它似乎是在碰撞發生的事情,並正在檢測它。但由於某些原因self.name和event.other.name是零。

回答

0

哦哇。幾個小時後,我終於明白了我的愚蠢,簡單的錯誤。

問題是我忘了給這艘船命名。代碼現在看起來像這樣,工作得很好:

function playGame() 
    -- Display the ship 
    ship = display.newRect(ship); 
    ship.name = "ship"; -- added this line to give the ship a name 
    shipLayer:insert(ship); 
    -- Add physics to ship 
    physics.addBody(ship, {density = 3, bounce = 0.3}); 

    ... 

    beginRun(); 
end 
0

嘗試使用:

top.name = "wall"; 

bottom.name = "wall"; 

top.myName = "wall" 

bottom.myName = "wall"; 

使用onCollision功能後,您的「createTunnel:功能:

-- Collision handler 
function onCollision(self, event) 

    if (event.phase == "began") then 
     print(self.myName .. ": collision began with " .. event.other.myName) 
    end 
end 
+0

我認爲我添加的.name屬性是一個自定義的?據我所知,任何類型的財產可以添加到盧阿表,這是其中之一。所以這個名字無關緊要。儘管如此,我改變了它。錯誤保持不變(除了現在名稱 - > myName)。此外,碰撞處理程序只在createTunnel之後被調用。我編輯了我原來的帖子,因爲我離開了。我仍然收到錯誤。我甚至嘗試將onCollision函數上方的createTunnel函數移到無效位置。 – Gakor