2015-08-22 71 views
0

我不確定這是否與我的for循環或矩形位置有關,但我已設置斷點並使用調試繪製來繪製矩形,並且它們顯示爲正確。Java for loop未運行完整循環

public void onAction(String name, boolean value, float tpf) { 
    if(name.equals("ShowInventory")){ 
     if(!value){ 
      if(Statics.s_ShowInventory == true){ 
       Statics.s_ShowInventory = false; 
      }else{ 
       Statics.s_ShowInventory = true; 
      } 
     } 
    } 

    if(name.equals("RightClick") && Statics.s_ShowInventory == true){ 
     Vector2f mousePos = screen.getMouseXY(); 
     for(int i = 0; i < 40; i++) 
     { 
      if(Main.inventory.inventorySlots[i].rect.Contains(mousePos)){ 
       System.out.println(Main.inventory.inventorySlots[i].slotNumber); 
      } 
     } 
    } 
} 

發生什麼事情是寫入控制檯的唯一矩形是第一個。我想要發生的是每次右鍵單擊爲true並且布爾值爲true時,循環遍歷矩形列表並找出哪個包含mousePos。當矩形被點擊時,控制檯中只出現「0」,所以我知道我沒有得到任何其他庫存槽號重疊。

另一件可能發生的事情是,循環可能沒有完全運行,這將是我的點擊方法中的問題。

public float x; 
public float y; 
public float width; 
public float height; 

public Rect(float x, float y, float width, float height){ 
    this.x = x; 
    this.y = y; 
    this.width = width; 
    this.height = height; 
} 

public boolean Contains(Vector2f pos){ 
    if(pos.x > x && pos.x < width && pos.y < height && pos.y > y){ 
     return true; 
    } 
    else 
     return false; 
} 


      Element e = createInventorySlot(i, x, y); 
      inventoryElements[i] = e; 
      inventorySlots[i] = new InventorySlot(i, 0, "empty", new Rect(inventoryElements[i].getPosition().x, inventoryElements[i].getPosition().y, iconSize, iconSize)); 
      e.setToolTipText(inventorySlots[i].itemName + " : " + inventorySlots[i].slotNumber + " : " + inventorySlots[i].quantity); 
    inventory.addChild(e); 
+0

這是不是很清楚你問什麼 - 對我來說,看起來如果這些庫存插槽不重疊,那麼你應該只希望看到一個打印。 – argentage

+0

我在問是否有什麼突出的東西會給我點擊時只讀取元素[0]的問題?如果我點擊任何其他inventorySlot,控制檯中不顯示任何內容。 – huehuehuehuehue

+0

我應該用什麼來代替?我有Vector2鼠標位置和一個矩形數組來檢查哪個矩形包含鼠標。 – huehuehuehuehue

回答

1

for循環一直循環。嘗試在每個循環中打印出if語句的狀態。

for(int i = 0; i < 40; i++) 
    { 
    // if(Main.inventory.inventorySlots[i].rect.Contains(mousePos)){ 
    //  System.out.println(Main.inventory.inventorySlots[i].slotNumber); 
    // } 

      System.out.println(Main.inventory.inventorySlots[i].rect.Contains(mousePos)); 
    } 

「.Contains」可能有問題,而不是for循環。 您的「.Contains」可能只能在第一個插槽中測試。這可以解釋爲什麼只有當鼠標位於第一個插槽時才能工作一次。另外檢查嘗試打印出自己的插槽列表,以確保您沒有40個第一個插槽的副本。

+0

插槽是另一個稱爲元素的類的副本,並且元素類不包含Rectangle類,所以我創建了一個以便爲鼠標位置使用Contains方法。不過,我會給這個鏡頭。 – huehuehuehuehue

+0

編輯爲包含Rect類。使用你的方法證明Contains在所有情況下都返回false – huehuehuehuehue

+0

嘗試打印pos.x和pos.y,併爲y值test test開關和< and >標誌 – Zanilen