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

时间:2017-06-02 14:04:18

标签: swift sprite-kit gameplay-kit

我试图让一个精灵朝着一个点移动,同时避开一些障碍。我使用的图表是GKObstacleGraph,从这个场景中获取:

enter image description here

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

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
}()

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

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!]
}

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

enter image description here

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

这是my project on GitHub

0 个答案:

没有答案