So I was trying to implement pathfinding in my SpriteKit game (the user touches the screen and a sprite makes its way to the touched point while avoiding obstacles). The following code is what i've gone for (this snippet is located in the custom class of the SpriteNode i want to move):
func move(location : CGPoint) {
let obstacles = SKNode.obstacles(fromNodeBounds: self.scene!.children.filter({ (n) -> Bool in
if (n.name ?? "" == "obstacle") {return true} else {return false}
}))
let graph = GKObstacleGraph.init(obstacles: obstacles, bufferRadius: 24)
let startNode = GKGraphNode2D.init(point: float2(Float(self.position.x), Float(self.position.y)))
let endNode = GKGraphNode2D.init(point: float2(Float(location.x), Float(location.y)))
graph.connectUsingObstacles(node: startNode)
graph.connectUsingObstacles(node: endNode)
let path : [GKGraphNode] = graph.findPath(from: startNode, to: endNode)
if (path.count <= 0) {return}
var actions = [SKAction]()
var bef = self.position
for n in path {
if let point2d = n as? GKGraphNode2D {
let point = CGPoint(x: CGFloat(point2d.position.x), y: CGFloat(point2d.position.y))
let moveAction = SKAction.move(to: point, duration: Double(distance(bef, point) * speed_multiplier))
let rotateAction = SKAction.rotate(toAngle: angle(bef, point), duration: 0, shortestUnitArc: true)
bef = point
actions.append(rotateAction)
actions.append(moveAction)
}
}
let sequence = SKAction.sequence(actions)
self.run(sequence)
}
i call this function from touchesMoved
in my gamescene-Class:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
...
let location = ((touches.first as? UITouch)?.location(in: self))!
ship.move(location: location)
...
}
This seems to work fine when i only tap the screen once, but when i tap and hold it, it moves a lot slower and the sprite starts to flicker. I tried fixing this for an hour now and i just have no idea what causes this weird behavior.
Thank you for your help!