I'm trying to minimize the size of a tile object when creating a 2d grid like tilemap. I create an array of short[,] and each [y,x] location corresponds to a id for a tile. To do this I create a class called TileType and have a struct Tile access the information from TileType about itself based on Its id. Like this:
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];
}
}
I found this by reading a post about how to efficiently store data for a map like this. I didn't write this and its just an example. But my question is how would I draw a tile onto the screen using this method? I would set up a way that the Texture would correspond to a source rectangle(TextureSource) in a tile atlas. But I dont understand how I would actually draw this. IE draw(Tile.Type.Id)? But Id is just a short.
First of all, you should fix a bug in initialization - when you create a type you should set an identifier in it. Like this:
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);
After this you can use Get by identifier method.
I'll explain the main idea of drawing all tiles in the screen (This is not a working code but it shows what you should do. Its simple:)):
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);
}
The implementation of DrawRectangleWithTexture depends on what developer environment do you use. Anyway, in this function you have all information to draw your image:
Rectangle is using for storing information about position and size of your image.
Texture is just a picture that you should draw.