因此,我试图在我的SpriteKit游戏中实现寻路(用户触摸屏幕,并且精灵会避开障碍物到达触摸点)。以下代码是我想要的(此代码段位于我要移动的SpriteNode的自定义类中):
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)
}
我在游戏场景类中从touchesMoved
调用此函数:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
...
let location = ((touches.first as? UITouch)?.location(in: self))!
ship.move(location: location)
...
}
当我只轻按一次屏幕时,这似乎工作正常,但是当我轻按并按住它时,它移动得慢得多,并且精灵开始闪烁。我尝试将其修复一个小时,但我不知道是什么原因导致了这种奇怪的行为。
谢谢您的帮助!