代理跟随路径无限期地向前移动

Ram*_*uri 6 sprite-kit swift gameplay-kit

我试图让精灵朝着一个点移动,同时避免一些障碍.我正在使用的图是GKObstacleGraph从这个场景获得的:

在此输入图像描述

为简单起见,我决定不使用圆形物理体来制作障碍物,但现在就足以使用精灵的界限了.这就是我创建图表的方式:

lazy var graph:GKObstacleGraph? =
{
    guard let spaceship = self.spaceship else { return nil }

    let obstacles = SKNode.obstacles(fromNodeBounds: self.rocks)
    let graph = GKObstacleGraph(obstacles: obstacles, bufferRadius: Float(spaceship.size.width))
    return graph
}()
Run Code Online (Sandbox Code Playgroud)

当用户点击场景的任何位置时,飞船应该通过避开障碍物开始向该位置移动:

func tap(locationInScene location:CGPoint)
{
    guard let graph = self.graph else { return }
    guard let spaceship = self.spaceship else { return }

    let startNode = GKGraphNode2D(point: vector_float2(withPoint: spaceship.position))
    let endNode = GKGraphNode2D(point: vector_float2(withPoint: location))

    graph.connectUsingObstacles(node: startNode)
    graph.connectUsingObstacles(node: endNode)

    let path = graph.findPath(from: startNode, to: endNode)
    print(path)
    let goal = GKGoal(toFollow: GKPath(graphNodes: path, radius: Float(spaceship.size.width)) , maxPredictionTime: 1.0, forward: true)
    let behavior = GKBehavior(goal: goal, weight: 1.0)
    let agent = GKAgent2D()
    agent.behavior = behavior

    graph.remove([startNode, endNode])
    spaceship.entity?.addComponent(agent)

    // This is necessary. I don't know why, but if I don't do that, I 
    // end up having a duplicate entity in my scene's entities array.
    self.entities = [spaceship.entity!]
}
Run Code Online (Sandbox Code Playgroud)

但当我点击场景中的一个点时,宇宙飞船开始无限向上移动.我试图打印GKAgent每一帧的位置,这就是我得到的:

在此输入图像描述

由于价值非常低,宇宙飞船仍然不停地向上移动.

这是我在GitHub上的项目.