SpriteKit SKTileMapNode detecting touched Tile
For solution used next posts:
To detect touched Tile of SKTileMapNode there are two functions to add to default new scene file
// Xcode Version 9.4.1 with Swift 4
// class TilemapScene: SKScene {
// ....
@objc func handleTapFrom(recognizer: UITapGestureRecognizer) {
if recognizer.state != .ended {
return
}
let recognizorLocation = recognizer.location(in: recognizer.view!)
let location = self.convertPoint(fromView: recognizorLocation)
guard let map = childNode(withName: "tileMapNode") as? SKTileMapNode else {
fatalError("Background node not loaded")
}
// Touched column and row detected here
let column = map.tileColumnIndex(fromPosition: location)
let row = map.tileRowIndex(fromPosition: location)
print(column as Any, row as Any)
// Getting optional userData if you have added userData in the TilemapEditor
let tile = map.tileDefinition(atColumn: column, row: row)
let mapData = map.userData?.value(forKey: "filledItems" ) as! Int
print(mapData as Any)
}
override func didMove(to view: SKView) {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.handleTapFrom(recognizer:)))
tapGestureRecognizer.numberOfTapsRequired = 1
view.addGestureRecognizer(tapGestureRecognizer)
}
// .... // }
