2015-10-04 71 views
0

我想在創建像tilemap一樣的二維網格時最小化圖塊對象的大小。我創建了一個short [,]數組,每個[y,x]位置對應一個tile的id。爲此,我創建一個名爲TileType的類並使用Tile Tile根據其id來訪問TileType中關於其自身的信息。就像這樣:使用結構從類獲取信息

struct Tile 
{ 
    short typeId; 
    public TileType Type 
    { 
      get 
      { 
        return TileType.Get(typeId); 
      } 
      set 
      { 
        typeId = value.Id; 
      } 
    } 

}

class TileType 
{  

    public short Id; 
    public string Name; 
    public Texture2D Texture; 
    public Rectangle TextureSource; 
    public bool IsObstacle; 


    static List<TileType> types; 
    static TileType() 
    { 
      types = new List<TileType>(); 
      var type = new TileType(); 
      type.Name = "Dirt"; 
      //initialize here 

      types.Add(type); 
    } 

    public static TileType Get(short id) 
    { 
      return types[id]; 
    } 

}

我通過閱讀有關如何有效地存儲數據的地圖喜歡這個職位發現這一點。我沒有寫這個,只是一個例子。但我的問題是如何使用這種方法在屏幕上繪製一個圖塊?我會設置一種方式,使紋理對應一個tile地圖集中的源矩形(TextureSource)。但我不明白我會如何畫這個。 IE繪製(Tile.Type.Id)?但是Id只是一個簡短的例子。

回答

0

首先,您應該修復初始化中的錯誤 - 當您創建一個類型時,您應該在其中設置一個標識符。像這樣:

var type = new TileType(); 
type.Id = 0; // This is unique identifier that we are using in Get method.  
type.Name = "Dirt"; 
type.Texture = new Texture2D(...); //Here you assign your texture for Dirt tile 
//Initialize position and size for your texture. 
type.TextureSource = new Rectangle(dirtStartX, dirtStartY, dirtWidth, dirtHeight); 
types.Add(type); 

type = new TileType(); 
type.Id = 0; // This is unique identifier that we are using in Get method.  
type.Name = "Water"; 
type.Texture = new Texture2D(...); //Here you assign your texture for Dirt tile 
//Initialize position and size for your texture. 
type.TextureSource = new Rectangle(waterStartX, waterStartY, waterWidth, waterHeight); 
types.Add(type); 

之後,您可以使用獲取標識符方法。

我會解釋繪製所有磚在屏幕的主要想法(這不是一個工作代碼,但它顯示了你應該做的其簡單的:)):

for (int id=0; id<TileTypeCount; id++) 
{ 
    TileType tileType = TileType.Get(id); //Get tile by its identifier. 
    //Now we have current texture and rectangle (position). Draw it 
    DrawRectangleWithTexture(tileType.Rectangle, tileType.Texture); 
} 

的DrawRectangleWithTexture的實施取決於您使用的開發人員環境。不管怎樣,在這個功能你把所有的信息繪製圖像:

  1. 矩形使用用於存儲圖像的位置和大小的信息。

  2. 紋理只是一張你應該畫的圖片。