From d8813acdb3cdc31aba6d9c684fe05eeff740fdb6 Mon Sep 17 00:00:00 2001 From: Ruben Labruyere Date: Wed, 21 Apr 2021 23:18:40 +0200 Subject: [PATCH] Added method GetSourceRect and made method GetSourceVector obsolete --- src/TiledMap.cs | 39 +++++++++++++++++++++++++++++++++++++++ src/TiledModels.cs | 23 +++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/src/TiledMap.cs b/src/TiledMap.cs index 291975c..bb5a1c1 100755 --- a/src/TiledMap.cs +++ b/src/TiledMap.cs @@ -363,6 +363,7 @@ public TiledTile GetTiledTile(TiledMapTileset mapTileset, TiledTileset tileset, /// An element within a TiledLayer.data array /// An int array of length 2 containing the x and y position of the source rect of the tileset image. Multiply the values by the tile width and height in pixels to get the actual x and y position. Returns null if the gid was not found /// This method currently doesn't take margin into account + [Obsolete("Please use GetSourceRect instead because with future versions of Tiled this method may no longer be sufficient")] public int[] GetSourceVector(TiledMapTileset mapTileset, TiledTileset tileset, int gid) { var tileHor = 0; @@ -387,6 +388,44 @@ public int[] GetSourceVector(TiledMapTileset mapTileset, TiledTileset tileset, i return null; } + + /// + /// This method can be used to figure out the source rect on a Tileset image for rendering tiles. + /// + /// + /// + /// + /// An instance of the class TiledSourceRect that represents a rectangle. Returns null if the provided gid was not found within the tileset. + public TiledSourceRect GetSourceRect(TiledMapTileset mapTileset, TiledTileset tileset, int gid) + { + var tileHor = 0; + var tileVert = 0; + + for (var i = 0; i < tileset.TileCount; i++) + { + if (i == gid - mapTileset.firstgid) + { + var result = new TiledSourceRect(); + result.x = tileHor * tileset.TileWidth; + result.y = tileVert * tileset.TileHeight; + result.width = tileset.TileWidth; + result.height = tileset.TileHeight; + + return result; + } + + // Update x and y position + tileHor++; + + if (tileHor == tileset.ImageWidth / tileset.TileWidth) + { + tileHor = 0; + tileVert++; + } + } + + return null; + } /// /// Checks is a tile is flipped horizontally diff --git a/src/TiledModels.cs b/src/TiledModels.cs index b82450c..f499c96 100644 --- a/src/TiledModels.cs +++ b/src/TiledModels.cs @@ -203,4 +203,27 @@ public class TiledTerrain /// public int tile; } + + /// + /// Used as data type for the GetSourceRect method. Represents basically a rectangle. + /// + public class TiledSourceRect + { + /// + /// The x position in pixels from the tile location in the source image + /// + public int x; + /// + /// The y position in pixels from the tile location in the source image + /// + public int y; + /// + /// The width in pixels from the tile in the source image + /// + public int width; + /// + /// The height in pixels from the tile in the source image + /// + public int height; + } } \ No newline at end of file