7

I am working with SpriteKit and draw a scene by the help of the scene editor in xcode. According to SpriteKit, we can use Navigation graph to draw the paths and I am able to draw a path using navigation graph but i am not able to access this object in swift back-end.

enter image description here

How to access this Navigation graph object from the scene.

Ron Myschuk
  • 6,011
  • 2
  • 20
  • 32
Araf
  • 510
  • 8
  • 32
  • @Ron did you know that? – Araf Jun 29 '17 at 10:32
  • This [SO Question](https://stackoverflow.com/questions/41207550/gameplaykit-scene-editor-navigation-graph-how-to-use-it-for-pathfinding) is discussing the same problem, with a workaround solution provided. – Mark Brownsword Jun 30 '17 at 22:35
  • 1
    @MarkBrownsword i got that question , its that case how to get that graph object grom my soritescene. – Araf Jul 01 '17 at 12:20

1 Answers1

4

In the default SpriteKit template the GameViewController has a section in the viewDidLoad function that copies over the Scene Editors Entities and Graphs.

class GameViewController: UIViewController {
    private var sceneNode: GameScene!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Load 'GameScene.sks' as a GKScene.
        if let scene = GKScene(fileNamed: "GameScene") {

            // Get the SKScene from the loaded GKScene
            if let sceneNode = scene.rootNode as! GameScene? {
                self.sceneNode = sceneNode

                self.sceneNode.entities = scene.entities // <-- entities loaded here
                self.sceneNode.graphs = scene.graphs // <-- graphs loaded here

                // ... other scene loading code
            }
        }
    }
}

These Entities and Graphs array variables are declared in the GameScene. Then retrieve the graph from the array.

class GameScene : SKScene {
    var entities = [GKEntity]()
    var graphs = [String : GKGraph]()
    var navigationGraph: GKGraph<GKGraphNode>!

    override func didMove(to view: SKView) {
       self.navigationGraph = self.graphs.values.first // <-- get a reference to your graph
    }
}

If there is more than one graph in the SpriteKit Editor, then use a query to retrieve it by name.

self.navigationGraph = self.graphs.values.first(where: {$0.name == "GraphName"})
Mark Brownsword
  • 2,287
  • 2
  • 14
  • 23