Calling costToNode: in subclassed GKGraphNode2D with GameplayKit

292 views Asked by At

Situation

I am using GKObstacleGraph for pathfinding on the following map: enter image description here

The orange areas are obstacles (GKPolygonObstacle), while the purple dots and lines are custom placed nodes (GKGraphNode2D) and their respective connections, which the entity can use to teleport through the obstacles.

Everything works fine and the entity finds the correct path: enter image description here

Goal

What I thought would be methodologically correct is to set the cost between the purple nodes to 0 (since they are portals). With this in mind, I first subclass all purple nodes as DoorGraphNodes:

import SpriteKit
import GameplayKit

class DoorGraphNode: GraphNode {

    var id: String!
    var floor: Int!
    var complement: DoorGraphNode!

    init(position: CGPoint, id: String, floor: Int) {
        self.id = id
        self.floor = floor
        let point = vector_float2(Float(position.x), Float(position.y))
        super.init(point: point)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setComplement(doorNode: DoorGraphNode) {
        self.complement = doorNode
    }
}

Then, I subclass all GKGraphNode2D nodes to be added to the GKObstaclesGraph as GraphNode:

import SpriteKit
import GameplayKit

class GraphNode: GKGraphNode2D {

    override func cost(to node: GKGraphNode) -> Float {
        if let fromNode = self as? DoorGraphNode {
            if let toNode = node as? DoorGraphNode {
                if fromNode.complement == toNode {
                    return 0.0
                }
            }
        }
        return self.cost(to: node)
    }
}

This way, when I call obstacleGraph.findPath(from: startNode, to: targetNode) then GameplayKit should theoretically receive 0.0 when it calls the costToNode: method between two connected (complement) purple (DoorGraphNode) nodes.

Problem

In practice though, I get an EXC_BAD_ACCESS error with no details in the console: enter image description here

I don't think I am doing something wrong logic-wise. Do you have any idea why this happens?

1

There are 1 answers

8
Mark Brownsword On

The line 22 in class GraphNode is calling itself. It should be calling its parent.

return super.cost(to: node)