### SKScene Setup with SKTilemapDelegate Source: https://github.com/mfessenden/sktiled/wiki/Setting-Up-Your-Scenes Shows how to load a Tiled map using a delegate for customization. Includes example delegate methods for modifying tilesets and setting up physics for object groups. ```swift class GameScene: SKScene, SKTilemapDelegate { var tilemap: SKTilemap! override func didMove(to view: SKView) { if let tilemap = SKTilemap.load(fromFile: "myTiledFile", delegate: self) { // add the tilemap to the scene addChild(tilemap) // center the tilemap in the scene tilemap.position.x = (view.bounds.size.width / 2.0) tilemap.position.y = (view.bounds.size.height / 2.0) self.tilemap = tilemap } } override func update(_ currentTime: TimeInterval) { // update tilemap self.tilemap?.update(currentTime) } func didAddTileset(_ tileset: SKTileset) { if (tileset.type == "Summer") { tileset.type = "Winter" } } func didRenderMap(_ tilemap: SKTilemap) { // finish setting up map here if let obstaclesLayer = tilemap.objectGroup(named: "Obstacles") { obstaclesLayer.isHidden = true obstaclesLayer.setupPhysics() } } } ``` -------------------------------- ### Output of Custom Setup Method Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Extending SKTiled.md Illustrates the expected console output when the `LevelScene.setupTilemap` method is called during map rendering, demonstrating the successful override. ```text # LevelScene: setting up tilemap: "level1" ``` -------------------------------- ### SKScene Setup with SKTilemapDelegate Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Scene Setup.md Loads a Tiled map using a delegate for customization. Demonstrates using `didRenderMap` to set up physics for an object group. Updates the tilemap in `update(_:)`. ```swift class GameScene: SKScene, SKTilemapDelegate { var tilemap: SKTilemap! override func didMove(to view: SKView) { if let tilemap = SKTilemap.load(fromFile: "myTiledFile", delegate: self) { // add the tilemap to the scene addChild(tilemap) // center the tilemap in the scene tilemap.position.x = (view.bounds.size.width / 2.0) tilemap.position.y = (view.bounds.size.height / 2.0) self.tilemap = tilemap } } func didRenderMap(_ tilemap: SKTilemap) { // finish setting up map here if let obstaclesLayer = tilemap.objectGroup(named: "Obstacles") { obstaclesLayer.isHidden = true obstaclesLayer.setupPhysics() } } override func update(_ currentTime: TimeInterval) { // update tilemap self.tilemap?.update(currentTime) } } ``` -------------------------------- ### Custom Tile Object for SKTilemapDelegate Source: https://github.com/mfessenden/sktiled/wiki/Setting-Up-Your-Scenes Provides an example of implementing the `objectForTile(named:)` delegate method to return a custom `SKTile.Type`, such as `MenuButtonTile`. ```swift class MainMenuScene: SKScene, SKTilemapDelegate { func objectForTile(named: String?) -> SKTile.Type { return MenuButtonTile.self } } ``` -------------------------------- ### Basic SKScene Setup for Tiled Map Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Scene Setup.md Loads a Tiled map in `didMove(to:)` and adds it to the scene. Centers the tilemap within the view's bounds. Updates the tilemap in `update(_:)`. ```swift class GameScene: SKScene { var tilemap: SKTilemap! override func didMove(to view: SKView) { // load a named map if let tilemap = SKTilemap.load(tmxFile: "myTiledFile") { addChild(tilemap) // center the tilemap in the scene tilemap.position.x = (view.bounds.size.width / 2.0) tilemap.position.y = (view.bounds.size.height / 2.0) self.tilemap = tilemap } } override func update(_ currentTime: TimeInterval) { // update tilemap self.tilemap?.update(currentTime) } } ``` -------------------------------- ### Add Tile with Physics Setup Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Add a new tile to a layer at a specified coordinate using its global ID and immediately set up its physics properties. This is useful for dynamically placing interactive elements in the game world. ```swift if let tile = tileLayer.addTile(at: 5, 8, gid: 32) { tile.setupPhysics(withSize: 8) } ``` -------------------------------- ### Add SKTiled Dependency via CocoaPods Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Getting Started.md Install SKTiled using CocoaPods by creating a Podfile and adding the SKTiled pod reference for your targets. Run 'pod install' to complete the setup. ```ruby pod init ``` ```ruby target 'iOS' do use_frameworks! # Pods for iOS pod 'SKTiled', '~> 1.23' end target 'macOS' do use_frameworks! # Pods for macOS pod 'SKTiled', '~> 1.23' end target 'tvOS' do use_frameworks! # Pods for tvOS pod 'SKTiled', '~> 1.23' end ``` ```bash pod install ``` -------------------------------- ### Setup Tile Physics Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Configure physics bodies for tile objects. The `isDynamic` parameter determines if the physics body is active or passive. This can be done using a predefined shape or a custom rectangle size. ```swift // create a physics body with a rectangle of size 8 tile.setupPhysics(shapeOf: .rectangle, isDynamic: true) // create a physics body with a rectangle of size 8 tile.setupPhysics(rectSize: CGSize(width: 8, height: 8), isDynamic: true) // setup dynamics on an array of tiles with a radius of 4 let dots = dotsLayer.getTilesWithProperty("type", "dot" as AnyObject) dots.forEach { $0.setupDynamics(radius: 4) } ``` -------------------------------- ### Accessing Tilesets by Name Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tilesets.md Query the tilemap node to get an inline tileset by its name. ```swift if let inlineTileset = tilemap.getTileset(named: "winter-tiles") { // do something with the tileset } ``` -------------------------------- ### SKTiledSceneDelegate Protocol Definition Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Scene Setup.md Defines the essential components for a standard game scene setup with SKTiled, including nodes for the world, camera, and tilemap. ```swift public protocol SKTiledSceneDelegate: class { /// World container node. Tiled assets are parented to this node. var worldNode: SKNode! { get set } /// Custom scene camera. var cameraNode: SKTiledSceneCamera? { get set } /// Tilemap node. var tilemap: SKTilemap? { get set } /// Load a tilemap from disk func load(tmxFile: String) -> SKTilemap? } ``` -------------------------------- ### Ignoring Custom Properties During SKTilemap Loading Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Tiled Properties.md Shows how to load a Tiled map while explicitly ignoring all custom properties. This is useful when custom properties are not needed or might interfere with scene setup. ```swift let tilemap = SKTilemap.load(tmxFile: "myTiledFile", ignoreProperties: true) ``` -------------------------------- ### Instantiating and Rendering a Map with Custom Delegate Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Extending SKTiled.md Shows how to instantiate a scene and load a tilemap using a custom delegate. The `LevelScene.setupTilemap` method will be called during map rendering. ```swift // the `LevelScene.setupMap` method will be called when the map is rendered: let levelScene = LevelScene(size: viewSize) if let tilemap = SKTilemap.load(tmxFile: level1, delegate: levelScene) { levelScene.tilemap = tilemap } ``` -------------------------------- ### Get Tile Vertices Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Retrieves the vertices that define the shape of a tile. ```swift let tileVerts = tile.getVertices() ``` -------------------------------- ### Getting Coordinate from Touch Event Source: https://github.com/mfessenden/sktiled/blob/master/README.md Determine the tilemap coordinate corresponding to the location of a touch event on a specific layer. ```swift // get the coordinate at the location of a touch event let touchLocation: CGPoint = objectsLayer.coordinateAtTouchLocation(touch) ``` -------------------------------- ### Initialize Graph with Walkable and Obstacle Tiles Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/GameplayKit.md Create a navigation graph for a tile layer by specifying walkable and obstacle tiles. Tiles are identified by custom properties in Tiled. ```swift let walkable = graphLayer.getTiles().filter { $0.tileData.walkable == true } let obstacles = graphLayer.getTiles().filter { $0.tileData.obstacle == true } let graph = graphLayer.initializeGraph(walkable: walkable, obstacles: obstacles, diagonalsAllowed: false)! ``` -------------------------------- ### Finding Tiles by Property Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Demonstrates how to find tiles based on any custom property and its value. ```APIDOC ## Finding Tiles by Property ### Description Query for tiles that possess a specific property with a given value. This can be any custom property defined for the tiles. ### Methods - `tilemap.getTilesWithProperty(_:_: )` ### Parameters - `propertyName` (String): The name of the property to search for. - `propertyValue` (Any): The value of the property to match. ### Code Example ```swift let fireTiles = tilemap.getTilesWithProperty("Attack", "Fire") let waterTiles = tilemap.getTilesWithProperty("isWater", true) ``` ``` -------------------------------- ### Get Layer Position with Pixel Offset Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Coordinates.md Calculates the position for a Tiled coordinate, allowing for additional pixel offsets in the x and y directions. ```swift // use CGFloat for offset let point = tileLayer.pointForCoordinate(3, 4, offsetX: 4, offsetY: 0) // use TileOffset for offset let point = tileLayer.pointForCoordinate(3, 4, offset: TileOffset.center) ``` -------------------------------- ### Add SKTiled Dependency via Carthage Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Getting Started.md To use Carthage, create a Cartfile and add the SKTiled repository. Run 'carthage update' to build the framework. ```bash github "mfessenden/SKTiled" ``` ```bash carthage update ``` ```bash carthage update --platform iOS ``` ```bash carthage update --use-xcframeworks ``` -------------------------------- ### Get Layer Position for a Tiled Coordinate Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Coordinates.md Calculates the position within a layer for a given Tiled coordinate. This is useful when adding objects to a layer. ```swift // get position in a layer for the given coordinate let point = tileLayer.pointForCoordinate(3, 4) ``` -------------------------------- ### Initializing GameplayKit Graph from Tile Layer Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/What's New.md Shows how to create a GameplayKit navigation graph from a tile layer, filtering tiles based on custom properties like 'walkable' and 'obstacle'. ```swift let walkable = tileLayer.getTiles().filter { $0.tileData.walkable == true } let obstacles = tileLayer.getTiles().filter { $0.tileData.obstacle == true } let graph = tileLayer.initializeGraph(walkable: walkable, obstacles: obstacles, diagonalsAllowed: false)! ``` -------------------------------- ### Tile Render Mode Configuration Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Demonstrates how to set the render mode for individual tiles to control their appearance and animation behavior. ```APIDOC ## Tile Render Mode Configuration ### Description Allows individual tiles to be configured for different rendering behaviors, such as ignoring animations or animating based on a global ID. ### Usage Set the `renderMode` property of an `SKTile` object. ### Modes - `default`: Tile renders at default settings. - `static`: Tile ignores any animation data. - `ignore`: Tile does not take into account its tile data. - `animated(globalID)`: Animate with a global id value. ### Code Example ```swift // Instruct tile to ignore animation tile.renderMode = TileRenderMode.static // Tile will animate with a global id of 129 tile.renderMode = TileRenderMode.animated(129) ``` ``` -------------------------------- ### Get Touch or Mouse Location in Layer Coordinates Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Coordinates.md Retrieves the location of a touch event (iOS) or mouse event (macOS) within the layer's coordinate system. ```swift // iOS with UITouch let touchPosition = tileLayer.touchLocation(touch) // OSX with NSEvent mouse event let eventPosition = tileLayer.mouseLocation(event: mouseEvent) ``` -------------------------------- ### Load Tilemap from File Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Maps.md Loads a Tiled tmx file and adds it to the scene's node hierarchy. Ensure the tmx file exists in your project's bundle. ```swift if let tilemap = SKTilemap.load(tmxFile: "MyTilemap.tmx") { worldNode.addChild(tilemap) } ``` -------------------------------- ### Initialize Graph with Walkable IDs Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/GameplayKit.md Initialize a tile layer's graph using an array of walkable tile IDs. Obstacle IDs can be provided as an empty array if not needed. ```swift let pathsLayer = tilemap.tileLayers(named: "Paths").first! let walkable: [Int] = [12, 13, 14, 42, 43, 44] let graph = graphLayer.initializeGraph(walkableIDs: walkable, obstacleIDs, [], diagonalsAllowed: false)! ``` -------------------------------- ### Get Coordinate at Touch or Mouse Event Location Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Coordinates.md Directly queries the Tiled coordinate corresponding to a touch or mouse event location. Each layer can provide different results based on its offset. ```swift // get the coordinate of a touch event let coord = tileLayer.coordinateAtTouchLocation(touch) // get the coordinate of a mouse event let coord = tileLayer.coordinateAtMouseEvent(event: event) ``` -------------------------------- ### Correct Subclassing with Protocol Default Methods Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Extending SKTiled.md Shows the correct way to handle protocol methods with default implementations when subclassing. The protocol method must be implemented on the base class that conforms to the protocol. ```swift // `LevelScene.objectForTileType` will be called as expected. class BaseScene: SKScene, SKTilemapDelegate { func objectForTileType(named: String?) -> SKTile.Type { return SKTile.self } } class LevelScene: BaseScene { override func objectForTileType(named: String?) -> SKTile.Type { return GameTile.self } } ``` -------------------------------- ### Adding and Managing Camera Delegates Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Scene Setup.md Demonstrates how to add a custom object as a delegate to the SKTiledSceneCamera to respond to zoom changes. Ensure to implement the delegate methods and add the object using `addDelegate`. ```swift extension Marker: SKTiledSceneCameraDelegate { func cameraZoomChanged(newZoom: CGFloat) { if (newZoom <= minZoom) { self.redraw(zoom: minZoom) } } } // create a new object & add it to the camera delegates let marker = Marker() cameraNode.addDelegate(marker) ``` -------------------------------- ### Control Layer Animation as SpriteKit Actions Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Maps.md Manually starts or stops SpriteKit actions for tile animations on a specific tilemap layer. This allows for fine-grained control over animation rendering per layer. ```swift // run SpriteKit actions for all animated tiles in the layer tileLayer.runAnimationAsActions() // remove all SpriteKit actions for the layer (stop tile animations) tileLayer.removeAnimationActions(restore: false) ``` -------------------------------- ### Accessing Layers by Name (New vs. Old) Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/What's New.md Demonstrates the updated method for retrieving layers by name, which now returns an array to accommodate potential name collisions in group layers. ```swift // old way if let groundLayer = tilemap.getLayer(named: "Ground") as? SKTileLayer { groundLayer.offset.x = 4.0 } // new way if let groundLayer = tilemap.getLayers(named: "Ground").first as? SKTileLayer { groundLayer.offset.x = 4.0 } ``` -------------------------------- ### Show All Objects in Scene Source: https://github.com/mfessenden/sktiled/wiki/Debugging Globally enable the visibility of all Tiled vector objects within the scene. ```swift tilemap.showObjects = true ``` -------------------------------- ### Generate Map Statistics for SKTiled Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Debugging.md Use the `SKTilemap.mapStatistics(default:)` method to get a detailed overview of the tilemap's layers, including their type, visibility, hierarchy, and spatial properties. This aids in debugging complex map structures. ```swift // This method is called without arguments to generate statistics. // Example usage would involve calling the method and printing its output: // print(tilemap.mapStatistics(default:)) // The output is a formatted string representing the scene hierarchy and layer properties. ``` -------------------------------- ### SKTiledSceneCamera Delegate Methods Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Scene Setup.md Optional methods for conforming objects to receive notifications about camera changes like position, zoom, and bounds. Includes platform-specific methods for touch and mouse events. ```swift // all platforms func cameraPositionChanged(newPosition: CGPoint) func cameraZoomChanged(newZoom: CGFloat) func cameraBoundsChanged(bounds: CGRect, position: CGPoint, zoom: CGFloat) // iOS only func sceneDoubleTapped(location: CGPoint) // macOS only func sceneDoubleClicked(event: NSEvent) func mousePositionChanged(event: NSEvent) ``` -------------------------------- ### Get Tile Data by Local ID Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Retrieve tile data using a local ID from a tileset object. This is useful when you have a reference to a tileset and need to access specific tile information based on its internal ID within that tileset. ```swift if let tiledata = tileset.getTileData(localID: 79) { print(tiledata) } // Tile ID: 78 @ 16x16, 6 frames ``` -------------------------------- ### Preloading External Tilesets Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tilesets.md Load multiple external tileset files and pass them to the tilemap parser during instantiation. ```swift let tilesetFiles = ["winter-tiles.tsx", "spring-tiles.tsx", "summer-tiles.tsx", "fall-tiles.tsx"] if let tilesets = SKTileset.load(tsxFiles: tilesetFiles) { // pass preloaded tilesets to parser if let tilemap = SKTilemap.load(tmxFile: "MyTilemap.tmx", withTilesets: tilesets) { worldNode.addChild(tilemap) } } ``` -------------------------------- ### Initializing and Adding an SKTile Node Source: https://github.com/mfessenden/sktiled/blob/master/README.md Create a new SKTile node from tile data and add it to the scene. Positions the tile using layer-specific coordinate conversion. ```swift let newTile = SKTile(data: tileData) scene.addChild(newTile) let tilePoint = groundLayer.pointForCoordinate(4, 5) tile.position = tilePoint ``` -------------------------------- ### Enable Grid and Bounding Shape Debugging Source: https://github.com/mfessenden/sktiled/wiki/Debugging Combine options to draw both the grid and the bounding shape of the tile map. ```swift tilemap.debugDrawOptions = [.drawGrid, .drawBounds] ``` -------------------------------- ### Finding Tiles by Type Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Shows how to query for tiles that have been assigned a specific string 'type' property. ```APIDOC ## Finding Tiles by Type ### Description Find all tiles within a tile layer or the entire tilemap that have been assigned a specific string type. ### Methods - `tilemap.getTiles(ofType:)` - `tileLayer.getTiles(ofType:)` ### Parameters - `type` (String): The type string assigned to the tiles. ### Code Example ```swift let allFireTiles = tilemap.getTiles(ofType: "Fire") let fireTiles = tileLayer.getTiles(ofType: "Fire") ``` ``` -------------------------------- ### Querying Layers Recursively Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/What's New.md Illustrates how to query for layers, specifying whether to search only top-level layers or the entire layer hierarchy. ```swift // query top-level layers let topLevelLayers = tilemap.getLayers(recursive: false) print(topLevelLayers.map { $0.layerName }) // ["Skyway", "Buildings", "Terrain"] // query all layers let allLayers = tilemap.getLayers(recursive: true) print(allLayers.map { $0.layerName }) // ["Skyway", "Paths", "Trees", "Buildings", "Roof", "Walls", "Foundation", "Terrain", "Ground", "Water"] ``` -------------------------------- ### Load a Tilemap Source: https://github.com/mfessenden/sktiled/blob/master/README.md Loads a Tiled map from a .tmx file and adds it to the scene. Ensure the TMX file is included in your project's assets. ```swift if let tilemap = SKTilemap.load(tmxFile: "sample-map") { scene.addChild(tilemap) } ``` -------------------------------- ### Load Tilemap with Delegate and Tileset Data Source Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Maps.md Loads a Tiled tmx file while specifying delegate and tileset data source objects. This allows for custom handling of tilemap events and tileset information. ```swift if let tilemap = SKTilemap.load(tmxFile: tmxFile, delegate: self as? SKTilemapDelegate, tilesetDataSource: self as? SKTilesetDataSource) { worldNode.addChild(tilemap) } ``` -------------------------------- ### Carthage Update Command Source: https://github.com/mfessenden/sktiled/wiki/Troubleshooting When encountering framework integration errors with Carthage, use the --no-use-binaries flag during the update process for SKTiled. ```shell carthage update --no-use-binaries ``` -------------------------------- ### Configure Development Team ID Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Getting Started.md Replace the placeholder with your Apple Development Team ID in the Demo.xcconfig file to manage code signing for demo projects. ```text SAMPLE_CODE_DISAMBIGUATOR = ${DEVELOPMENT_TEAM} ``` -------------------------------- ### Workaround for Subclassing Protocol Default Methods Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Extending SKTiled.md Demonstrates a workaround for the subclassing issue by implementing a secondary method in the superclass that can be overridden by the subclass. This allows custom logic in subclasses. ```swift class BaseScene: SKScene, SKTilemapDelegate { func didRenderMap(_ tilemap: SKTilemap) { // call a secondary method setupTilemap(tilemap) } func setupTilemap(_ tilemap: SKTilemap) { print("BaseScene: setting up tilemap: \"\(tilemap.name!)\"") } } class LevelScene: BaseScene { override func setupTilemap(_ tilemap: SKTilemap) { print("LevelScene: setting up tilemap: \"\(tilemap.name!)\"") } } ``` -------------------------------- ### Create a Tile Object Source: https://github.com/mfessenden/sktiled/wiki/Working-with-Objects Manually create a tile object using the SKObjectGroup.newTileObject method with tile data. Animated tiles are supported. ```swift if let tileData = tilemap.getTileData(globalID: 23) { if let tileObject = objectGroup.newTileObject(data: tileData) { tileObject.position = objectGroup.pointForCoordinate(10, 5) } } ``` -------------------------------- ### Configure TiledGlobals Defaults Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Other API Features.md Modify default settings for frame color, retrieve the framework version, and set debug callbacks for mouse events using TiledGlobals. ```swift // set the debug frame color TiledGlobals.default.debug.frameColor = SKColor(hexString: "#FA6400") // get the framework version let version = TiledGlobals.default.version // set the debug callbacks for mouse events TiledGlobals.default.debug.mouseFilters = [.tileCoordinates, .tileDataUnderCursor, .tilesUnderCursor] ``` -------------------------------- ### Show Objects in Each Object Layer Source: https://github.com/mfessenden/sktiled/wiki/Debugging Iterate through all object layers and enable the visibility of their objects. ```swift // show objects in each object layer for layer in tilemap.objectLayers { layer.showObjects = true } ``` -------------------------------- ### Enable Tile Bounds Debugging Source: https://github.com/mfessenden/sktiled/wiki/Debugging Visualize the shapes of individual tiles within a tile layer. ```swift tileLayer.debugDrawOptions = .drawTileBounds ``` -------------------------------- ### Load Tilemap with Dynamic Update Mode Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Maps.md Loads a tilemap and configures it to only update animated tiles, optimizing performance by reducing unnecessary updates. This is the default behavior. ```swift // tilemap will update only animated tiles if let tilemap = SKTilemap.load(tmxFile: "MyTilemap.tmx", delegate: nil, updateMode: TileUpdateMode.dynamic) { } ``` -------------------------------- ### Create a Tile Object Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Objects.md Manually create a tile object within an object group using tile data obtained from the tilemap. Supports animated tiles if the source tile data is animated. ```swift // add a tile object for global id 23 if let tileData = tilemap.getTileData(globalID: 23) { if let tileObject = objectGroup.newTileObject(data: tileData) { tileObject.position = objectGroup.pointForCoordinate(10, 5) } } ``` -------------------------------- ### Querying Tiles by Global ID Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Explains how to find tiles using their global unique identifier across all tilesets. ```APIDOC ## Querying Tiles by Global ID ### Description Retrieve tiles that match a specific global ID, applicable to both individual tile layers and the entire tilemap. ### Methods - `tilemap.getTiles(globalID:)` - `tileLayer.getTiles(globalID:)` ### Parameters - `globalID` (Int): The global ID of the tiles to query. ### Code Example ```swift // Query tiles from the tile map node let tiles = tilemap.getTiles(globalID: 10) // Query tiles from the parent layer let tiles = tileLayer.getTiles(globalID: 10) ``` ``` -------------------------------- ### SKTiledSceneDelegate Protocol Definition Source: https://github.com/mfessenden/sktiled/wiki/Setting-Up-Your-Scenes Defines the essential components and methods for setting up a game scene with SKTiled. Implement this protocol to customize your scene's interaction with tilemaps. ```swift public protocol SKTiledSceneDelegate: class { /// Root container node. Tiled assets are parented to this node. var rootNode: SKNode! { get set } /// Custom scene camera. var cameraNode: SKTiledSceneCamera! { get set } /// Tile map node. var tilemap: SKTilemap! { get set } /// Load a tilemap from disk, with optional tilesets func load(tmxFile: String, inDirectory: String?, withTilesets tilesets: [SKTileset], ignoreProperties: Bool, buildGraphs: Bool, loggingLevel: LoggingLevel) -> SKTilemap? } ``` -------------------------------- ### Accessing and Querying Tile Properties Source: https://github.com/mfessenden/sktiled/wiki/Tiled-Properties Demonstrates how to access, check for, retrieve, and remove custom properties from tile data using SKTiled's SKTiledObject protocol methods. ```swift // access tile data properties tileData.properties // query an object to see if it has a named property floorObject.hasKey("slippery") // get tile data that have a named property (regardless of value) let dynamicObjects = tilemap.getTileData(withProperty: "mass") // get tile data that have a named property (with a specific value) let heavyDynamicObjects = tilemap.getTileData(withProperty: "mass", "10.0") // removing a named property returns the value (or nil if it doesn't exist) if let levelName = tilemap.removeProperty(forKey: "levelName") { print("Level name was '\(levelName)'") } ``` -------------------------------- ### Creating a New Tile Layer Source: https://github.com/mfessenden/sktiled/wiki/Working-With-Layers Instantiate a new tile layer and assign it a name. The layer is automatically parented to the SKTilemap node. ```swift // create a new tile layer let newTileLayer = tilemap.newTileLayer(named: "Walls") ``` -------------------------------- ### Add Run Script Phase to Clean Metadata Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Troubleshooting.md Integrate this script into your Xcode build phases to automatically clean image metadata during compilation. ```bash xattr -rc $PROJECT_DIR/Assets/. ``` -------------------------------- ### Xcode Import Paths for zlib Source: https://github.com/mfessenden/sktiled/wiki/Troubleshooting Ensure zlib is correctly linked in your Xcode project's build settings by adding its module path to the Swift Compiler - Search Paths. ```text SWIFT_INCLUDE_PATHS = "zlib"; ``` -------------------------------- ### Query and Update Text Objects Source: https://github.com/mfessenden/sktiled/wiki/Working-with-Objects Query text objects by their content and update their displayed text dynamically. Ensure the object is sized appropriately in Tiled to avoid clipping. ```swift if let scoreObject = objectGroup.getObjects(withText: "SCORE").first { scoreObject.text = "2000" } ``` -------------------------------- ### List File Attributes in Shell Source: https://github.com/mfessenden/sktiled/wiki/Troubleshooting Use this command to check for and identify extended file metadata that might cause code signing issues in Xcode. ```shell ls -al@ ``` -------------------------------- ### Querying Tile Data by Local ID Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Details how to retrieve tile data using a local ID within a specific tileset. ```APIDOC ## Querying Tile Data by Local ID ### Description Obtain tile data using a local ID relative to a specific tileset. The local ID is calculated as the tileset's `firstgid` plus the tile's internal ID. ### Method - `tileset.getTileData(localID:)` ### Parameters - `localID` (Int): The local ID of the tile within the tileset. ### Code Example ```swift // Assuming tileset has firstgid = 1 if let tiledata = tileset.getTileData(localID: 79) { print(tiledata) } // Expected Output: Tile ID: 78 @ 16x16, 6 frames ``` ``` -------------------------------- ### Load Tiled Map as Folder Reference Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Getting Started.md When assets are added as folder references in Xcode, use this Swift code to load a Tiled map by specifying the directory name. This offers more flexibility in project organization. ```swift if let tilemap = SKTilemap.load(tmxFile: "MyTilemap.tmx", inDirectory: "Tiled") { scene.addChild(tilemap) } ``` -------------------------------- ### Find Tiles by Custom Property Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Retrieve tiles based on any custom property and its value, not just the 'type' property. This allows for flexible querying based on various attributes assigned to tiles. ```swift let fireTiles = tilemap.getTilesWithProperty("Attack", "Fire") let waterTiles = tilemap.getTilesWithProperty("isWater", true) ``` -------------------------------- ### Querying All Objects Source: https://github.com/mfessenden/sktiled/blob/master/README.md Retrieve all SKTileObject instances from the tilemap. ```swift let allObjects = tilemap.getObjects() ``` -------------------------------- ### Highlight Individual Tiles in SKTiled Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Debugging.md Highlight specific tiles for a duration using `SKTile.highlightDuration` and `SKTile.showBounds`. This is useful for indicating selected or interactive tiles. ```swift // highlight the tile for .25 seconds tile.highlightDuration = 0.25 tile.showBounds = true ``` -------------------------------- ### Adding a Tile to a Layer Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Explains how to add a new tile to a specific layer at a given coordinate using its global ID, with options for physics and tile type. ```APIDOC ## Adding a Tile to a Layer ### Description Add a new tile to a specified layer at a given coordinate using its global tile ID (gid). Optionally configure physics and assign a tile type. ### Method - `tileLayer.addTile(at:gid:tileType:)` ### Parameters - `x` (Int): The x-coordinate for the new tile. - `y` (Int): The y-coordinate for the new tile. - `gid` (Int): The global ID of the tile to add. - `tileType` (String, optional): A custom type string for the tile. ### Usage - Call `setupPhysics(withSize:)` on the returned tile to enable physics. - The `tileType` parameter can be used with the `SKTilemapDelegate.objectForTileType` protocol method. ### Code Example ```swift // Add a tile with global ID 32 at coordinate (5, 8) if let tile = tileLayer.addTile(at: 5, 8, gid: 32) { tile.setupPhysics(withSize: 8) } // Add a tile with a custom type 'Wall' if let wallTile = tileLayer.addTile(at: 2, 17, gid: 145, tileType: "Wall") { wallTile.hitMaxCount = 3 } ``` ``` -------------------------------- ### Load Tiled Map as Bundled Asset Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Getting Started.md Use this Swift code to load a Tiled map that has been bundled directly into your Xcode project. Ensure the tileset and image are in the same directory as the map file. ```swift if let tilemap = SKTilemap.load(tmxFile: "MyTilemap.tmx") { scene.addChild(tilemap) } ``` -------------------------------- ### Default SKTilemapDelegate Implementation Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Extending SKTiled.md Provides default implementations for returning SKTile, SKTileObject, and GKGridGraphNode types. Use this as a base for custom scene classes. ```swift class GameScene: SKScene, SKTilemapDelegate { func objectForTileType(named: String?) -> SKTile.Type { return SKTile.self } func objectForVectorType(named: String?) -> SKTileObject.Type { return SKTileObject.self } func objectForGraphType(named: String?) -> GKGridGraphNode.Type { return GKGridGraphNode.self } } ``` -------------------------------- ### Accessing Tile Data by Property or Type Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tilesets.md Query tile data based on an arbitrary property or the 'type' property. ```swift let breakables = tilemap.getTileData(withProperty: "breakable") let lights = tilemap.getTileData(ofType: "light") ``` -------------------------------- ### Set Tile Render Mode to Animated Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Use this to make a tile animate using a global ID. Specify the global ID of the animation to use. ```swift tile.renderMode = TileRenderMode.animated(129) ``` -------------------------------- ### Show Objects in a Specific Object Layer Source: https://github.com/mfessenden/sktiled/wiki/Debugging Enable the visibility of objects for a single, designated object layer. ```swift // show objects for `one` object layer collisionsLayer.showObjects = true ``` -------------------------------- ### Set Tile Render Mode to Static Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Use this to instruct a tile to ignore any animation data. This is useful for tiles that should not animate. ```swift tile.renderMode = TileRenderMode.static ``` -------------------------------- ### Accessing and Controlling Animated Tiles Source: https://github.com/mfessenden/sktiled/blob/master/README.md Retrieve all animated tiles recursively or from a specific layer. Control animation playback by pausing or reversing speed. ```swift // get all animated tiles, including nested layers let allAnimated = tilemap.animatedTiles(recursive: true) // pause/unpause tile animation for tile in allAnimated { tile.isPaused = true } // run animation backwards for tile in allAnimated { tile.speed = -1.0 } // get animated tiles from individual layers let layerAnimated = groundLayer.animatedTiles() ``` -------------------------------- ### Query and Update Text Object Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Objects.md Find a text object by its content and update its displayed text dynamically. Ensure the object is sized appropriately in Tiled to prevent clipping. ```swift if let scoreObject = objectGroup.getObjects(withText: "SCORE").first { // update the rendered text scoreObject.text = "2000" } ``` -------------------------------- ### Querying Tiles by Custom Property and Value Source: https://github.com/mfessenden/sktiled/blob/master/README.md Retrieve tiles from a layer or the entire tilemap that possess a specific custom property with a given boolean value. ```swift let groundWalkable = groundLayer.getTilesWithProperty("walkable", true) let allWalkable = tilemap.getTilesWithProperty("walkable", true") ``` -------------------------------- ### Creating a New Tile Layer Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Layers.md Creates a new tile layer and optionally parents it to a specific group layer within the SKTilemap. ```swift // create a new tile layer let newTileLayer = tilemap.newTileLayer(named: "Walls") ``` ```swift // create a new tile layer and parent it to an existing group let houseGroup = tilemap.groupLayer(named: "HOUSE").first! let newTileLayer = tilemap.newTileLayer(named: "Walls", group: houseGroup) ``` -------------------------------- ### Apply Custom Shader to SKTilemap Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Maps.md Load a custom shader from the project and apply it to an SKTilemap node. This requires enabling effects rendering first and passing the map's render size as a shader attribute. ```swift // emable effects rendering on the map node tilemap.shouldEnableEffects = true // load a shader from the current project let shader = SKShader(fileNamed: "waves") // create an attribute to pass the tilemap's render size to the shader as an attribute shader.attributes = [SKAttribute(name: "a_map_size", type: .vectorFloat2)] // set the tilemap shader tilemap.shader = shader // pass the tilemap size to the shader tilemap.setValue(SKAttributeValue(vectorFloat2: tilemap.sizeInPoints.toVec2), forAttribute: "a_map_size") ``` -------------------------------- ### Querying Tiles by Custom Property Type Source: https://github.com/mfessenden/sktiled/blob/master/README.md Retrieve tiles that have been assigned a specific custom property type (e.g., 'fire') in Tiled. ```swift if let fireTiles = tilemap.getTiles(ofType: "fire") { // do something fiery here... } ``` -------------------------------- ### Set Layer Highlight Color for All Tiles Source: https://github.com/mfessenden/sktiled/wiki/Debugging Apply a uniform highlight color to all tiles within a specific tile layer. ```swift // set the highlight color for *all* tiles in the layer tileLayer.highlightColor = SKColor.blue ``` -------------------------------- ### Add Tile with Custom Type Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Add a tile to a layer with a specified global ID and a custom tile type string. This allows for custom logic and delegation based on the tile's type. ```swift if let wallTile = tileLayer.addTile(at: 2, 17, gid: 145, tileType: "Wall") { // set the custom tile property wallTile.hitMaxCount = 3 } ``` -------------------------------- ### Enable Object Layer Bounds Debugging Source: https://github.com/mfessenden/sktiled/wiki/Debugging Visualize the bounding shapes of objects within a specific object layer. ```swift objectgroup.debugDrawOptions = .drawObjectBounds ``` -------------------------------- ### Query Objects by Type Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Objects.md Retrieve objects of a specific type from an object group or recursively from the entire tilemap. The recursive search is optional. ```swift // query objects from the layer let emitterObjects = objectsGroup.getObjects(ofType: "Emitter") // query objects from the map node let allEmitterObjects = tilemap.getObjects(ofType: "Emitter", recursive: true) ``` -------------------------------- ### Accessing External Tilesets by Filename Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tilesets.md Retrieve an externally saved tileset using its TSX filename. ```swift if let externalTileset = tilemap.getTileset(fileNamed: "winter-tiles.tsx") { // do something with the tileset } ``` -------------------------------- ### Enable Map Bounding Shape Debugging Source: https://github.com/mfessenden/sktiled/wiki/Debugging Use `debugDrawOptions` to visualize the bounding shape of the tile map. ```swift tilemap.debugDrawOptions = .drawObjectBounds ``` -------------------------------- ### Adding an SKNode as a Child to a Layer Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Working with Tiles.md Illustrates how to add any SKNode to a tile layer at a specific coordinate, with options for offset and z-position. ```APIDOC ## Adding an SKNode as a Child to a Layer ### Description Add any `SKNode` instance to a tile layer at a specified coordinate. Convenience methods allow for positioning with offsets and z-position. ### Methods - `tileLayer.addChild(_:_:_:offset:zpos:)` - `tileLayer.addChild(_:_:_:dx:)` ### Parameters - `node` (SKNode): The node to add. - `x` (Int): The x-coordinate. - `y` (Int): The y-coordinate. - `offset` (CGPoint, optional): An offset to apply to the node's position. - `zpos` (Int, optional): The z-position for the node. - `dx` (Int, optional): An offset applied only to the x-coordinate. ### Code Example ```swift // Add a child node with coordinate, offset, and zPosition tileLayer.addChild(tile, 5, 8, offset: CGPoint(x: 4.0, y: 8.0), zpos: 50) // Add a child node with coordinate and x-offset tileLayer.addChild(tile, 5, 8, dx: 4) ``` ``` -------------------------------- ### Custom Tile Object for Main Menu Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Scene Setup.md Specifies a custom tile type (`MenuButtonTile.self`) for use within a specific scene. This allows for scene-specific tile behaviors. ```swift class MainMenuScene: SKScene, SKTilemapDelegate { /// use a custom tile type for the main menu func objectForTile(named: String?) -> SKTile.Type { return MenuButtonTile.self } } ``` -------------------------------- ### Set Individual Tile Highlight Color Source: https://github.com/mfessenden/sktiled/wiki/Debugging Customize the highlight color for individual tiles using the `highlightColor` property. ```swift // set the tile highlight color for individual tiles tile.highlightColor = SKColor.red ``` -------------------------------- ### SKTilemapDelegate Protocol Definition Source: https://github.com/mfessenden/sktiled/wiki/Setting-Up-Your-Scenes Defines the delegate protocol for interacting with SKTilemap during parsing and rendering. Implement these methods to customize tilemap behavior and object types. ```swift protocol SKTilemapDelegate { func didBeginParsing(_ tilemap: SKTilemap) // Called when the map is instantiated. func didAddTileset(_ tileset: SKTileset) // Called when a tileset has been added. func didAddLayer(_ layer: SKTiledLayerObject) // Called when a layer has been added. func didReadMap(_ tilemap: SKTilemap) // Called before layers begin rendering. func didRenderMap(_ tilemap: SKTilemap) // Called when layers are finished rendering. func objectForTile(named: String?) -> SKTile.Type // Tile object type for use with tile layers. func objectForVector(named: String?) -> SKTileObject.Type // Vector object type for use with object groups. func objectForGraph(named: String?) -> GKGridGraphNode.Type // Navigation graph node type. } ``` -------------------------------- ### SKTilemapDelegate Protocol Definition Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Documentation/Scene Setup.md Defines the delegate protocol for interacting with SKTilemap during parsing and rendering. Implement these methods to customize tilemap behavior. ```swift protocol SKTilemapDelegate { // Called when the map is instantiated. func didBeginParsing(_ tilemap: SKTilemap) // Called when a tileset is about to be render a spritesheet. func willAddSpriteSheet(_ tileset: SKTileset, fileNamed: String) -> String // Called when a tileset has been added. func didAddTileset(_ tileset: SKTileset) // Called when a layer has been added. func didAddLayer(_ layer: SKTiledLayerObject) // Called before layers begin rendering. func didReadMap(_ tilemap: SKTilemap) // Called when layers are finished rendering. func didRenderMap(_ tilemap: SKTilemap) // Tile object type for use with tile layers. func objectForTile(named: String?) -> SKTile.Type // Vector object type for use with object groups. func objectForVector(named: String?) -> SKTileObject.Type // Navigation graph node type. func objectForGraph(named: String?) -> GKGridGraphNode.Type } ``` -------------------------------- ### Querying Tiles by Global ID Source: https://github.com/mfessenden/sktiled/blob/master/README.md Retrieve tiles from a specific layer that match a given global tile ID. ```swift if let waterTiles = waterLayer.getTiles(globalID: 17) { // do something watery here... } ``` -------------------------------- ### Access Default TiledGlobals Singleton Source: https://github.com/mfessenden/sktiled/blob/master/Docs/Sections/Globals.md Access the default `TiledGlobals` singleton to configure global settings for SKTiled. This object allows setting default values for API objects and controlling debugging functions. ```swift let globals = TiledGlobals.default ```