2014-02-27 88 views
0

我有一個2d數組,代表我的遊戲地圖的碰撞和前景層。我試圖根據玩家的位置來獲取適當的圖塊來讀取圖塊的編號。但是,當我從數組中調用特定的圖塊時,它會返回錯誤的數字或說Cannot read property 'index here' of undefined。我已經通過查看數組來驗證玩家位置的索引應該返回一個非零值,但是它們會返回零或未定義的消息。下面是我使用找到瓷磚位置的代碼:JavaScript 2d數組返回錯誤數據

if (layers[i]["name"] === "collision") { 
       var colLayer = layers[i]; 
       var tileWidth = colLayer["tilesize"]; 

       x /= tileWidth; 
       y /= tileWidth; 

       var dataArr = colLayer["data"]; 

       console.log("X " + dataArr.length + " Y " + dataArr[0].length) 

       try { 
        console.log(Math.floor(x) + " " + Math.floor(y+1) + " Block num is " + dataArr[Math.floor(y)][Math.floor(x)]); 
        if (dataArr[Math.floor(x)][Math.floor(y)]) 
         return true; 
       } catch (err) { 
        console.log(err); 
       } 
      } 

,這裏是供參考的數據陣列:

"data": [ 
       [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], 
       [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], 
       [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], 
       [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], 
       [1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,0,12,12,12,12,12,0,0,0,0,0,0,1], 
       [1,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,24,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], 
       [1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1], 
       [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1], 
       [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] 
      ] 
+0

您還應該添加'console.dir(dataArr)',以確保您確實處理了您認爲自己的對象。 – Pointy

回答

1

我很久以前做了這樣的事情。我們很習慣(X, Y)的座標,但是在數組中它實際上就是(Y, X)

所以dataArr[Math.floor(x)][Math.floor(y)]應該是dataArr[Math.floor(y)][Math.floor(x)]

試試看看它是否有效。

+0

就是這樣。之前我在做這件事,但我忘了我需要爲y補充1來補償玩家的身高。謝謝。 – Slayter