I'm writing a game using SpriteKit and GameplayKit, where a lot of entities use pathfinding logics to move around. Therefore I want run the pathfinding code in the background. However, I occasionally get a EXC_BAD_ACCESS error from either of these line:
scene.obstacleGraph.connectUsingObstacles(node: startNode)
scene.obstacleGraph.connectUsingObstacles(node: endNode)
Here is the code for my pathfinding logic:
func findPathToTarget(targetLocation: CGPoint) {
DispatchQueue.global(qos: .background).async {
unowned let scene = enemyEntity.spriteComponent.node.scene as! WorldScene
let startNode = GKGraphNode2D(point: vector_float2(Float(enemyEntity.spriteComponent.node.position.x), Float(enemyEntity.spriteComponent.node.position.y)))
let endNode = GKGraphNode2D(point: vector_float2(Float(targetLocation.x), Float(targetLocation.y)))
scene.obstacleGraph.connectUsingObstacles(node: startNode)
scene.obstacleGraph.connectUsingObstacles(node: endNode)
let pathNodes = scene.obstacleGraph.findPath(from: startNode, to: endNode) as! [GKGraphNode2D]
DispatchQueue.main.async {
scene.obstacleGraph.remove([startNode, endNode])
}
guard pathNodes.count > 1 else { return }
let attackPath = GKPath(graphNodes: pathNodes, radius: 16.0)
enemyEntity.agent!.behavior = GKAgentBehaviors.followPath(forAgent: enemyEntity.agent!, speed: enemyEntity.stats[.movementSpeed]!, onPath: attackPath)
}
}
I'm not experienced at working with GCD, therefore I'd like to have a better understanding of it. Can someone please tell me what I'm doing wrong with the DispatchQueue in the my code.
Thank you for any help.