0

I am using SKTilemapNode. How I can use the Pathfinding with GameplayKit properly?

Some Info: Walls are all tiles and no tiles are 'ways'

Lirf
  • 111
  • 12
  • 1
    this youtuber uses pathfinding within the SKEditor pretty extensively.. It's not a tutorial, but he has successfully implemented pathfinding in his game. https://www.youtube.com/user/Veeneck/videos. Also, you will probably need to watch the related WWDC 2016 videos apple has on their website concerning this. – Fluidity Feb 06 '17 at 22:05

2 Answers2

6

This is how I implemented a GKGridGraph using the contents of one of my tile maps:

    let graph = GKGridGraph(fromGridStartingAt: vector_int2(0,0), width: Int32(tileMap.numberOfColumns), height: Int32(tileMap.numberOfColumns), diagonalsAllowed: false)

    var obstacles = [GKGridGraphNode]()

    for column in 0..<tileMap.numberOfColumns
    {
        for row in 0..<tileMap.numberOfRows
        {
            let position = tileMap.centerOfTile(atColumn: column, row: row)

            guard let definition = tileMap.tileDefinition(atColumn: column, row: row) else { continue }

            guard let userData = definition.userData else { continue }
            guard let isObstacle = userData["isObstacle"] else { continue }

            if isObstacle
            {
                let wallNode = graph.node(atGridPosition: vector_int2(Int32(column),Int32(row)))!
                obstacles.append(wallNode)
            }
        }
    }

    graph.remove(obstacles)

I had to set the isObstacle property in the userData field of my obstacle tile:

enter image description here

This way you get the resulting grid graph without the osbtacles.

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
  • 1
    For anyone using this snippet...the graph is setup for the wrong dimensions. It is setup for wide = columns and height = columns. If you have an rectangular size grid you'll have to change it to height = rows – Ron Myschuk Feb 23 '18 at 15:34
3

The basic idea is to create a SKGridGraph of connected nodes, then remove the nodes that can't be walked on. The GameplayKit Guide shows an example (Listing 6-1 Generating a Grid Graph). So in your case using SKTilemapNode the graphs width and height is determined by the number of tile wide and high on the map e.g. if your map is 32 tiles wide and 18 tiles high, then initialise the graph with width of 32 and height of 18.

Mark Brownsword
  • 2,287
  • 2
  • 14
  • 23
  • Do you have a good tutorial for SKGridGraph? the Guide you posted is not that good for me – Lirf Feb 08 '17 at 13:44
  • [This tutorial](http://in8bits.com/gameplaykit-in-swift-a-tower-defence-game-part-3/) is a good example of building a Tower Defence game with SpriteKit and GameplayKit. It uses the `SKGridGraph`. – Mark Brownsword Feb 08 '17 at 19:59