2015-08-23 20 views
3

我使用的是2維的布爾數組,以檢查其中一個實體是我的2D側滾輪的內部以及碰撞。我知道我不是在尋找一個實體離開的程度有多高或多低,這是故意的。當我運行這個代碼時,它說最近的實體距離15個單元格。但是,當我運行我的代碼時,它說離開最近的實體是15個塊。此外,當我打印出來distanceX它打印出以下幾點: 15.我不知道爲什麼它不會註冊爲9即使這是它接收的第一近距離,也是最接近的。通過掃描二維布爾數組找到最接近真正的協調

我不能發佈圖片的又一但原因0,0,2,和2得到印刷是因爲我對我的球員的所有四個角被認爲在網格中真正的4個矩形所以它檢測到兩個上彼此的頂部以及網格中其他2或2個點。由於我不能上傳圖片,請嘗試查看我製作的這張圖片的含義。 https://lh3.googleusercontent.com/OLSDPshjeU0YMahcmc0MDk-NocBMoG-7iN2xFTeFsQ8mAfF-sEPD8NBqXP4ENoN4YWmfUQ=s114

感謝您的幫助!

//Loop through my grid of booleans 
    for (int x = 0; x < map.getMapGrid().length; x++) { 
     for (int y = 0; y < map.getMapGrid().length; y++) { 
      //For comparison 
      Long distance = Long.MAX_VALUE; 
      // The second part of the if statement is to make sure it is checking for 
      // entities that arent the floor, therefor one above the grid position of the player 
      if (map.getMapGrid()[x][y] && y > ((Player) player).getGridPositionLeft().y - 1){ 
       // distanceX = where something true was found (x) - where the player is in the grid 
       // Ex: 1 - 4 = |-3|, there is an entity 3 away 
       distanceX = Math.abs((int)(x - ((Player) player).getGridPositionLeft().x)); 

       // if the distance of the entity from the player is less then the comparison variable, 
       // the closest entity x coordinate is distanceX 
       if(distanceX < distance){ 
        closestCoord.x = distanceX; 
        closestCoord.y = 0; 
       } 
      } 
     } 
    } 

    return closestCoord; 
} 

回答

2
Long distance = Long.MAX_VALUE; 

該變量從未被重新分配,因此它總是具有價值Long.MAX_VALUE

而且聲明它的最裏面的循環中,所以它會在每個迭代復位。如果你想迭代之間要記住一個變量的值,你需要聲明和初始化的循環。

+0

我會嘗試這 – Luke

+0

我做了這個,現在它說離我最近的實體是0格,這是因爲它正好在我的球員的位置,你知道我怎麼可以從我的答案中排除這個結果而不完全否定0嗎? – Luke

+0

如果玩家所處的位置永遠不存在實體,則可以添加* x *和* y *不能等於玩家座標的條件。否則,你需要能夠判斷一個實體是否與玩家位置完全相同,並且我無法從查看你發佈的代碼中看到怎麼做。 – tom