TiledSharp
ナビゲーションに移動
検索に移動
TiledSharpとは、ゲームにおけるタイルマップ(2Dマップ)のデファクトスタンダード形式である「TMXファイル」および「TSXファイル」を.NET FrameworkおよびMonoで手軽に扱うためのライブラリである。地図関連の「TileSharp」というライブラリと一文字違いでありNuGet検索に出てこない事件に注意すること。
概要
Cocos2DにはCCTiledMapというTMXファイルを扱うクラスが標準で用意ように、その派生であるCocosSharpでもCCTileMapというクラスが標準で用意されている。しかし(2016年12月時点では)CocosSharpはXamarin.Macで動かないようなので、生のMonoGameでもTMXファイルを手軽に扱えないかな、CocosSharpのソースから依存部分を削って移植するのめんどくさいな、と軟弱な気持ちでググっていたら出てきた。素晴らしい。
似たようなライブラリは他にもありそうな感じだったが、TiledSharpは依存関係がなく、MonoGame + Xamarin.Macでも安心して使えそうな感じだったので試してみた。
使い方
準備
NuGetで「TiledSharp」と検索してぶち込め。
MonoGameでの例
MonoGameでのTiledSharp使用例。 読み込みと描画周り。
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
TmxMap map;
Texture2D tileset;
int tileWidth;
int tileHeight;
int tilesetTilesWide;
int tilesetTilesHigh;
// 〜〜〜中略〜〜〜
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TMXファイルを読み込む
map = new TmxMap("Content/exampleMap.tmx");
// タイルセットを読み込む
tileset = Content.Load<Texture2D>(map.Tilesets[0].Name.ToString());
tileWidth = map.Tilesets[0].TileWidth;
tileHeight = map.Tilesets[0].TileHeight;
tilesetTilesWide = tileset.Width / tileWidth;
tilesetTilesHigh = tileset.Height / tileHeight;
}
// 〜〜〜中略〜〜〜
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
for (var i = 0; i < map.Layers[0].Tiles.Count; i++)
{
int gid = map.Layers[0].Tiles[i].Gid;
if (gid == 0)
{// 空タイルは何もしない
}
else
{
int tileFrame = gid - 1;
int col = tileFrame % tilesetTilesWide;
int row = (int)Math.Floor((double)tileFrame / (double)tilesetTilesWide);
float x = (i % map.Width) * map.TileWidth;
float y = (float)Math.Floor(i / (double)map.Width) * map.TileHeight;
var tilesetRec = new Rectangle(tileWidth * col, tileHeight * row, tileWidth, tileHeight);
spriteBatch.Draw(tileset, new Rectangle((int)x, (int)y, tileWidth, tileHeight), tilesetRec, Color.White);
}
}
spriteBatch.End();
base.Draw(gameTime);
}
}
関連項目
- MonoGame
- Tiled Map Editor - TMXファイルの総本山