8

I am trying to subclass GKGraphNode2D to also include different penalties for different terrains (in the costToNode method). When I create a new GKGraph with an array of my new subclass and call findPathFromNode on the GKGraph, it ignores my costToNode method entirely.

The code looks like:

public class PenaltyGraphNode: GKGraphNode2D {

    public let penalty: Float

    init(position: CGPoint, penalty: Float) {
        self.penalty = penalty
        let point = vector_float2(Float(position.x), Float(position.y))
        super.init(point: point)
    }

    override public func costToNode(node: GKGraphNode) -> Float {

        guard let penaltyNode = node as? PenaltyGraphNode else { return super.costToNode(node) }

        return super.costToNode(node) * (1 + penaltyNode.penalty)
    }
}

And where I am trying to use the GKGraph (node creation removed for brevity sake):

let penaltyNodes: [PenaltyGraphNode] = [penaltyNode1, penaltyNode2, ...]

let graph = GKGraph(nodes: penaltyNodes)
let path = graph.findPathFromNode(startNode, toNode: endNode) as? [PenaltyGraphNode]

The costToNode in my subclass is never getting called, I made sure that all of the nodes that I create in the graph and add to it later are all PenaltyGraphNodes, but it still won't call costToNode. When I print the graph's nodes property, it shows them as GKGraphNode2D objects only, not my subclass.

Am I missing something obvious here?

Marcus
  • 839
  • 8
  • 14
  • I believe this is a duplicate of my question asked a few weeks ago (http://stackoverflow.com/questions/31975084/subclassing-gkgraphnode-gkgraphnode2d-in-gameplaykit), which has an example project demonstrating the issue. I've also included an Apple bug report that can be duplicated, drawing attention to this issue. – Tim Arnold Sep 02 '15 at 13:15
  • Additionally, check the response of your node objects to the `class` message. With a naïve print-out of the `description` property (used when printed with `NSLog`), it does look like the objects are vanilla `GKGraphNode2D` objects, but when I interrogate them further, they are indeed my subclass, as expected. However, `costToNode:` etc. are still not called. – Tim Arnold Sep 02 '15 at 13:16
  • I'm seeing the same thing, logging the nodes only shows that they are GKGraphNode2D objects, but looking deeper they are definitely my subclass – Marcus Sep 03 '15 at 03:36

0 Answers0