2014-06-21 23 views
0

我有它gameobjects列表,我有一點的代碼,他們繪製到屏幕我的遊戲對象從我的列表中出來的順序是什麼?

for (int i = Gameobject.gameobjects.Count -1; i >= 0 ; i--) 
{   
    if (Gameobject.gameobjects[i] is GameItem || 
     Gameobject.gameobjects[i] is MenuItem || 
     Gameobject.gameobjects[i] is Rock || 
     Gameobject.gameobjects[i] is ChaseSprite|| 
     Gameobject.gameobjects[i] is MenuBar|| 
     Gameobject.gameobjects[i] is MenuBarItem) 
    {  
    Gameobject.gameobjects[i].Draw(spriteBatch);        
    #if Debug 
    drawBorder(Gameobject.gameobjects[i].BoundingBox, 2, Color.Red); 
    spriteBatch.DrawString(spritefont,Rock.rockpieces.Count.ToString() , new Vector2(200, 200), Color.Pink); 
    #endif 

}               
}  

的問題是,它似乎並沒有得出任何特定的對象順序,在我的情況下menuItems正在繪製在菜單欄下,使得它在遊戲運行時不會顯示菜單項。現在我知道menuItem正在繪製,因爲我將菜單欄設置爲50%透明,當您將鼠標在它上面,當我將鼠標懸停在上面時,您可以清楚地看到菜單項。對我來說,這是一個巨大的問題,因爲我已經組織了我的遊戲。

+0

您希望他們在什麼順序?爲什麼不訂購GameObject.gameobjects集合,或按順序組裝它? – brumScouse

回答

1

爲此,您使用的這種集合可以影響對象的順序。如果gameobjectsList,它們應該按照您使用的順序gameobjects.Add

您在if..is..||測試列表中指定的項目順序僅僅表示它們在測試中的順序 - 它絕不會對它們進行排序,因爲您只是在說,如果不強迫一個項目等待爲了另一個。

解決此問題的一種方法是應用LINQ,可以通過多個循環或通過OrderBy調用。

UPDATE如果編輯通話的過程中收集,確保具有結果通過ToArrayToList

foreach(var gameObj in Gameobject.gameobjects 
    .OrderBy(SortGameObject) 
    .ToArray()) // This will force iteration and cache the result, so changes to the orignal collection don't throw an exception 
{ 
    gameObj.Draw(spriteBatch);        
    #if Debug 
    drawBorder(gameObj.BoundingBox, 2, Color.Red); 
    spriteBatch.DrawString(spritefont,Rock.rockpieces.Count.ToString() , new Vector2(200, 200), Color.Pink); 
    #endif 
} 

private static int SortGameObject(Gameobject target) 
{ 
    if (target is GameItem)  return 0; 
    else if (target is MenuItem) return 1; 
    else if(target is Rock)  return 2; 
    else if(target is ChaseSprit) return 3; 
    else if(target is MenuBar)  return 4; 
    else if(target is MenuBarItem) return 5; 
    else       return int.MaxValue; // This forces any draws on unrecognized objects to go on top 
                 // - to put unrecognized objects on the bottom, use -1 instead 
} 

複製查詢到一個數組或列表,這可能是比較容易解決所有這些繼承父類型,然後有一個DrawOrder參數,這可能會減少查詢

foreach(var gameObj in Gameobject.gameobjects.OrderBy(g => g.DrawOrder)) 
... // Draw calls as above 
+0

對不起,如果這是一個基本的問題,但如果SortGameObject方法無效如何返回0?你還回來了什麼? – koss

+0

因爲我完全忘了返回int。我會在答案中解決這個問題。 – David

+0

它是否必須是一個靜態的 – koss

相關問題