TKMap Class Reference

Inherits from NSObject
Conforms to TKPropertiesOwner
Declared in TKMap.h

Overview

Represents a tilemap. A Map is typically created by loading a TMX file.

Loading a TMX file

TKMap* map = [TKMap mapWithContentsOfFile:@"MMORPGMOBARTSF2P.tmx"];

Creating an empty Map

You can also start with an “empty” tilemap:

TKMap* map = [TKMap map];

When creating an empty Map instance, it will not work unless you add at least one Tileset and one Layer.

To generate Map content at runtime it will generally be easier to create a barebones, minimal TMX file in Tiled first. That way you can set up the things that would be cumbersome to edit and maintain in code, for instance the tilesets and tile collisions. Then modify the map instance after loading as needed.

Creating an empty Tilemap

+ map

Creates an empty (non-functional) map instance. You’ll have to fill it with the necessary data, ie layers, tilesets and such before use.

+ (nonnull instancetype)map

Declared In

TKMap.h

Creating a Tilemap from TMX file

+ mapWithContentsOfFile:

Creates a TKMap instance from a TMX file.

+ (nullable instancetype)mapWithContentsOfFile:(nonnull NSString *)file

Parameters

file

The path to a TMX file in the bundle.

Return Value

A new TKMap instance, or nil if there were any errors. Use the error object to learn more about the error.

Discussion

Note: TMX file must use Base64 encoding and can either be uncompressed, or zlib or gzip compressed. Zlib compression is recommended (best compression, fastest loading). CSV and XML formats are not currently supported.

Declared In

TKMap.h

+ mapWithContentsOfFile:error:

Creates a TKMap instance from a TMX file.

+ (nullable instancetype)mapWithContentsOfFile:(nonnull NSString *)file error:(NSError *__autoreleasing __nullable *__nullable)error

Parameters

file

The path to a TMX file in the bundle.

error

An error object. May be nil.

Return Value

A new TKMap instance, or nil if there were any errors. Use the error object to learn more about the error.

Discussion

Note: TMX file must use Base64 encoding and can either be uncompressed, or zlib or gzip compressed. Zlib compression is recommended (best compression, fastest loading). CSV and XML formats are not currently supported.

Declared In

TKMap.h

Writing a Tilemap to TMX file

– writeToFile:directory:compression:error:

Writes the map in TMX format to the file, with optional compression. The tile layer data will be base64 encoded.

- (nullable NSString *)writeToFile:(nonnull NSString *)file directory:(NSSearchPathDirectory)directory compression:(TKDataCompression)compression error:(NSError *__autoreleasing __nullable *__nullable)error

Parameters

file

The file (with optional path component) to write the file to.

directory

The NSSearchPathDirectory to which the file is relative to. Must be a user-writable location.

compression

A TKDataCompression value that specifies whether and how to compress the tile layer data.

error

Optional error object. Is non-nil when NO is returned.

Return Value

The absolute path to the file that was written, or nil if there was an error.

Discussion

If in doubt regarding NSSearchPathDirectory, here’s what’s recommended:

  • Use NSApplicationSupportDirectory if the file location is managed by your app and the user shouldn’t normally be able to use this file outside your app. Ie use this for savegames.
  • Use NSDocumentDirectory if you want to give the user easy access to the file from outside your app, for instance loading it in Tiled. Ie use this for Tilemap editors.

On iOS the decision should also take into account whether you want the file to be backed up by iCloud or not. See: http://stackoverflow.com/a/12371323/201863 (and the links on that page)

Declared In

TKMap.h

Map Name

  name

The name of the map. Maps loaded with the TMX reader will have the TMX filename as their name by default.

@property (copy, nonnull) NSString *name

Declared In

TKMap.h

Map and Tile Dimensions

  size

The size of the tilemap, in grid coordinates.

@property TKSize size

Declared In

TKMap.h

  sizeInPoints

The size of the tilemap, in points.

@property (readonly) CGSize sizeInPoints

Declared In

TKMap.h

  gridSize

The size of the grid, in points. Typically but not necessarily equivalent to the width & height of a tile.

@property TKSize gridSize

Declared In

TKMap.h

Rendering Modifiers

  backgroundColor

The tilemap’s background color, encoded as string in typical HTML color code format, ie #aabbcc for the RGB values. Defaults to black, ie #000000.

@property (copy, nonnull) NSString *backgroundColor

Return Value

The background color as hex-encoded string.

Discussion

Note: Use tk_colorWithString(backgroundColor to convert the string to a TKColor instance.

Declared In

TKMap.h

  orientation

The TKMapOrientation of a tilemap. Defaults to TKMapOrientationOrthogonal.

@property TKMapOrientation orientation

Declared In

TKMap.h

  staggerAxis

The axis along which tiles are “staggered” (shifted).

@property TKStaggerAxis staggerAxis

Discussion

Note: Only meaningful for “staggered” isometric and hexagonal maps.

Declared In

TKMap.h

  staggerIndex

Whether tiles are position-shifted on even or odd rows/columns (depending on staggerAxis).

@property TKStaggerIndex staggerIndex

Discussion

Note: Only meaningful for “staggered” isometric and hexagonal maps.

Declared In

TKMap.h

  hexSideLength

Length of hexagonal tile’s sides. Determines the spacing of tiles on the hex grid. Value can be negative though that is not recommended and typically not useful. Typically the value is half of tileWidth or tileHeight, depending on staggerAxis. If it’s less than half the tiles it will force the tiles to overlap, which is often used to make hex tiles align seamlessly, ie for a tile width of 60 hexSideLength could be set to 28 for a minimal overlap.

@property NSInteger hexSideLength

Discussion

Note: Only meaningful for hexagonal maps.

Declared In

TKMap.h

  tileDrawOrder

The TKTileDrawOrder of the tilemap. Defaults to TKTileDrawOrderRightDown.

@property TKTileDrawOrder tileDrawOrder

Declared In

TKMap.h

Map and Tile Properties

  properties

The map’s custom properties (TKProperties).

@property (nonnull) TKProperties *properties

Discussion

Note: In Tiled you can edit the tilemap properties by choosing Map Properties from the Map menu, then add or edit Custom Properties at the bottom of the properties list.

Declared In

TKMap.h

– propertiesForTile:

The custom properties for a specific tile GID.

- (nullable TKProperties *)propertiesForTile:(TKTileGID)tile

Parameters

tile

The tile GID whose properties to get.

Return Value

The TKProperties object or nil if the tile has no custom properties.

Declared In

TKMap.h

– setProperties:forTile:

Assigns properties to a specific tile. If the tile already has properties the new properties will replace the existing ones (properties are not merged).

- (void)setProperties:(nonnull TKProperties *)properties forTile:(TKTileGID)tile

Parameters

properties

The TKProperties to assign to the tile.

tile

The global tile GID to assign the properties to.

Declared In

TKMap.h

– tilesForPropertyNamed:value:

Returns all tile GIDs (as NSNumber) which have a property with the given name and value. All tilesets in the map are enumerated.

- (nonnull NSArray<NSNumber*> *)tilesForPropertyNamed:(nullable NSString *)property value:(int32_t)value

Parameters

property

The name of a property whose value should be compared.

value

The value that the property must match.

Return Value

An array containing NSNumber objects, sorted by tile GID in ascending order (lowest first, highest last). If no tiles matched the property name and value an empty array is returned. *

Discussion

By passing nil for the value parameter, the method will return all tile GIDs which have a property of the given kind/name regardless of the property’s value.

Declared In

TKMap.h

– tileValuesForPropertyNamed:

Returns the values of tile GIDs in all tilesets which have a property of the given name. The returned dictionary contains tile GIDs (as NSNumber) for keys and the dictionary’s values are the property’s values (also as NSNumber).

- (nonnull NSDictionary<NSNumber*,NSNumber*> *)tileValuesForPropertyNamed:(nonnull NSString *)property

Parameters

property

The name of a property.

Return Value

A dictionary of property values with tile GIDs as keys, both wrapped in NSNumber. Returns an empty dictionary if no tiles with matching property were found.

Declared In

TKMap.h

Working with Tilesets

  tilesets

List of TKTileset instances used by this map’s tile layers and “tile” objects.

@property (readonly, nonnull) NSArray<TKTileset*> *tilesets

Declared In

TKMap.h

– addTileset:

Adds a tileset.

- (void)addTileset:(nonnull TKTileset *)tileset

Parameters

tileset

The TKTileset to add to the tilemap. It must not already be added.

Declared In

TKMap.h

– removeTileset:

Removes a tileset.

- (void)removeTileset:(nonnull TKTileset *)tileset

Parameters

tileset

The TKTileset to remove from the tilemap.

Declared In

TKMap.h

– tilesetForTile:

Obtains the tileset associated with a specific tile GID. Useful to access that tile’s tileset or the tile’s properties.

- (nullable TKTileset *)tilesetForTile:(TKTileGID)tile

Parameters

tile

The tile GID for which you like to obtain its TKTileset instance.

Return Value

The TKTileset the tile is part of, or nil if the tile is invalid.

Declared In

TKMap.h

– tilesetNamed:

Obtains a tileset by its name.

- (nullable TKTileset *)tilesetNamed:(nonnull NSString *)name

Parameters

name

The name of the tileset.

Return Value

The TKTileset with matching name or nil if there’s no tileset with that name.

Discussion

Note: Tileset names are case-sensitive.

Declared In

TKMap.h

Working with Layers

  layers

List of layers (TKLayer) used by this map. Array is sorted in the draw order which is the reverse order the layers appear in Tiled’s Layers list (bottom-most = first layer (index 0), top-most = last layer).

@property (readonly, nonnull) NSArray<TKLayer*> *layers

Return Value

An array of TKLayer objects.

Declared In

TKMap.h

– addLayer:

Adds a layer to the end of the layers list. The layer must not already be added to a tilemap.

- (void)addLayer:(nonnull TKLayer *)layer

Parameters

layer

The TKLayer to add.

Declared In

TKMap.h

– insertLayer:atIndex:

Inserts a layer at the given index of the layers list. If index is out of bounds, the layer is added to the end of the list. The layer must not already be added to a tilemap.

- (void)insertLayer:(nonnull TKLayer *)layer atIndex:(NSUInteger)index

Parameters

layer

The TKLayer to add.

index

The index the layer should be added to.

Declared In

TKMap.h

– removeLayer:

Removes a layer from the list of layers.

- (void)removeLayer:(nonnull TKLayer *)layer

Parameters

layer

The TKLayer to remove.

Declared In

TKMap.h

– layerNamed:

Obtains a layer by its name.

- (nullable TKLayer *)layerNamed:(nonnull NSString *)name

Parameters

name

The name identifying a layer.

Return Value

The TKLayer with matching name or nil if there’s no layer with that name.

Discussion

Note: Layer names are case-sensitive.

Declared In

TKMap.h

Working with Tile Animations

– addTileAnimation:

Adds a TKTileAnimation, provided that the instance has a unique name. If there is already an animation of the same name, the new animation will replace the previous one. If the associated tile has properties, the animation will assign those tile properties prefixed with “anim.”. That’s also how you can set the animation’s name in Tiled, by adding a tile property and name it anim.name.

- (void)addTileAnimation:(nonnull TKTileAnimation *)animation

Parameters

animation

A TKTileAnimation instance with a valid name.

Declared In

TKMap.h

– tileAnimationForTile:

Get a tile animation by its associated (global) tile GID.

- (nullable TKTileAnimation *)tileAnimationForTile:(TKTileGID)tile

Parameters

tile

The global tile GID. Any flags will be masked out.

Return Value

A TKTileAnimation instance, or nil if there’s no tile animation associated with the tile GID.

Declared In

TKMap.h

– tileAnimationNamed:

Get a tile animation by its name. The name can be set in Tiled by editing the tile’s properties and adding a property named anim.name.

- (nullable TKTileAnimation *)tileAnimationNamed:(nonnull NSString *)name

Parameters

name

The name assigned to the tile animation.

Return Value

A TKTileAnimation instance, or nil if there’s no tile animation by this name.

Declared In

TKMap.h

Working with Objects

  nextObjectID

Used to store the next available unique object ID. Every time a new object is created, it is supposed to get nextObjectID assigned as its unique ID, incrementing nextObjectID.

@property NSUInteger nextObjectID

Declared In

TKMap.h

GameplayKit Methods

– gridGraphForTileLayersNamed:diagonalsAllowed:

Returns a grid graph for the given tile layers where all non-empty tiles (non-zero GID) have a graph node.

- (nonnull GKGridGraph *)gridGraphForTileLayersNamed:(nonnull NSArray<NSString*> *)tileLayers diagonalsAllowed:(BOOL)diagonalsAllowed

Parameters

tileLayers

The names of tile layers where any non-empty tile creates a graph node.

diagonalsAllowed

Whether diagonal connections should be created. Same parameter as in GKGridGraph.

Return Value

A GKGridGraph with GKGridGraphNode instances for all coordinates with non-empty tiles on any of the given tile layers.

Discussion

This makes it very easy to create a tile layer for pathfinding, then just draw any tile on that layer for any coordinate that should become “walkable”. You don’t have to use tile properties or consider GID values at all for this approach, making it suitable for prototyping and simple games. But this workflow becomes more tedious and error prone the more TMX files (levels) you have, and the more often you make changes that affect pathfinding.

Note: A tile needs only be set on one of the supplied tile layers for a graph node to exist at this coordinate.

Declared In

TKMap+GameplayKit.h

– gridGraphForTileLayersNamed:walkableTiles:blockedTiles:diagonalsAllowed:

Returns a grid graph for the given tile layers, with graph nodes depending on the combination of walkableTiles and blockedTiles tiles.

- (nonnull GKGridGraph *)gridGraphForTileLayersNamed:(nonnull NSArray<NSString*> *)tileLayerNames walkableTiles:(nullable NSArray<NSNumber*> *)walkableTiles blockedTiles:(nullable NSArray<NSNumber*> *)blockedTiles diagonalsAllowed:(BOOL)diagonalsAllowed

Parameters

tileLayerNames

The names of tile layers with which to compare the walkableTiles and blockedTiles.

walkableTiles

A list of GID (as NSNumber) that, if they appear on any of the tileLayers, should add a graph node at the tile’s coordinate.

blockedTiles

A list of GID (as NSNumber) that, if they appear on any of the tileLayers, should remove the graph node at the tile’s coordinate.

diagonalsAllowed

Whether graph nodes also connect diagonally. Same parameter as in GKGridGraph. Ignored for hexagonal maps.

Return Value

A GKGridGraph with GKGridGraphNode instances.

Discussion

This function enables you to use different pathfinding tile layers to generate different graphs for different unit types. For example, ground units could share the same graph with flying units, but the flying units' graph would be extended by also including the flying units tile layer in the layers list. That way you could allow flying units to move over elevations and water.

The walkableTiles list will create graph nodes for any matching tile GID that appears on any of the provided tileLayers. The blockedTiles list will remove graph nodes for any matching tile GID that appears on any of the provided tileLayers.

If walkableTiles is nil or empty, only blockedTiles will be used to remove undesirable graph nodes. If blockedTiles is nil or empty, only walkableTiles will cause graph nodes to remain in the grid graph.

If both walkableTiles and blockedTiles are given, the same coord is tested on all layers to be in either set. Whatever test succeeds last causes the graph node to be either removed or retained. This is mostly useful for using one layer that defines all potentially walkable tiles for any unit type, then using other blocking layers that remove some of these graph nodes.

For instance the potentially walkable tiles could encompass all tiles walkable by flying units, while another layer removes graph nodes that ground units can not reach, with a third layer further removing any land tiles that ship units must not “walk on”. If you call the method three times with different layers you end up with three different graphs for these three different unit types.

If both walkableTiles and blockedTiles are nil or empty, the function creates graph nodes for all non-empty tiles on the tileLayers. This is the same behavior as when using [TKMap gridGraphForTileLayersNamed:diagonalsAllowed:].

Note: The list of tileLayers is enumerated in sequence, meaning you can use an “additive” layer first, then poke holes in the graph with additional “blocking” layers. Or vice versa: use a “blocking” layer that removes many graph nodes, then have one or more “additive” layers that add graph nodes back in. Both approaches work equally well, there is no preference. For each game you need to evaluate which approach is going to provide a better workflow.

Note: Only the final result after evaluating all layers for a given coordinate causes the grid graph to be updated. The function assumes that the grid graph is filled from the beginning (the default behavior of GKGridGraph) so it mostly removes grid graph nodes, it rarely adds any (only when one layer removed, then a later layer added a node).

Declared In

TKMap+GameplayKit.h

– gridGraphForTileLayersNamed:costs:diagonalsAllowed:

Similar to [TKMap gridGraphForTileLayersNamed:walkableTiles:blockedTiles:diagonalsAllowed:] except that you pass in a dictionary of costs (key: tile GID, value: cost). Any tile GID in the costs dictionary with a non-zero positive value is considered “walkable” and creates a grid node of TKGridGraphNode that gets the cost value assigned to its cost property. Any tile GID not in the costs dictionary or whose cost value is zero or negative will be considered “blocked” and will have its corresponding grid node removed from the graph.

- (nonnull GKGridGraph *)gridGraphForTileLayersNamed:(nonnull NSArray<NSString*> *)tileLayerNames costs:(nonnull NSDictionary<NSNumber*,NSNumber*> *)costs diagonalsAllowed:(BOOL)diagonalsAllowed

Parameters

tileLayerNames

The names of tile layers whose tiles to consider.

costs

A dictionary with NSNumber tile GIDs as keys and NSNumber float values representing that tile’s “cost to node”.

diagonalsAllowed

Whether graph nodes also connect diagonally. Same parameter as in GKGridGraph. Ignored for hexagonal maps.

Return Value

A GKGridGraph with TKGridGraphNode instances.

Declared In

TKMap+GameplayKit.h

– obstacleGraphForObjectLayersNamed:bufferRadius:

Creates an obstacle graph based on the objects on one or more object layers.

- (nonnull GKObstacleGraph *)obstacleGraphForObjectLayersNamed:(nonnull NSArray<NSString*> *)objectLayerNames bufferRadius:(float)bufferRadius

Parameters

objectLayerNames

The names of object layers where objects are placed that represent the GKObstacle instances.

bufferRadius

How much space to leave between nodes and the obstacle. Same paramerter as in GKObstacleGraph init.

Return Value

A GKObstacleGraph with obstacles created from object layers.

Discussion

Valid obstacle objects are: rectangle, polygon, tile. Ellipse and polyline objects on the object layers will be ignored.

Declared In

TKMap+GameplayKit.h