【问题标题】:GameplayKit find path to moving spriteGameplayKit 找到移动精灵的路径
【发布时间】:2017-11-30 23:41:16
【问题描述】:

我想要一个精灵跟随玩家,我试图通过 GameplayKit 的 Pathfinding 来实现这一点。这是有效的,但有问题。我使用以下代码获取从敌人精灵到玩家精灵的路径:

func moveEnemy(to playerPos: CGPoint){
    guard !moving else { return }
    moving = true
    let startNode = GKGraphNode2D(point: float2(Float(self.position.x), Float(self.position.y)))
    let endNode = GKGraphNode2D(point: float2(Float(playerPos.x), Float(playerPos.y)))

    PhysicsHelper.graph.connectUsingObstacles(node: startNode)
    PhysicsHelper.graph.connectUsingObstacles(node: endNode)
    let path = PhysicsHelper.graph.findPath(from: startNode, to: endNode)
    guard path.count > 0 else{ return }

    var actions = [SKAction]()
    for node in path{
        if let point2d = node as? GKGraphNode2D{
            let point = CGPoint(x:CGFloat(point2d.position.x) , y:CGFloat(point2d.position.y))
            let action = SKAction.move(to: point, duration: 1)
            actions.append(action)
        }
    }
    let seq = SKAction.sequence(actions)
    self.run(seq) {
        self.moving = false
    }
}

这是在这个块中我的敌人的另一个函数中调用的:

case .follow:
    if allowMovement{
        if self.action(forKey: "Hurt") == nil{
           //   orientEnemy(to: playerPos)
              moveEnemy(to: playerPos)
           //   animateWalk()
        }
    }

并且这个函数在我的GameScene的update函数中被调用在这个block中:

if enemy.checkCircularIntersection(player: player, node: enemy, radius: 40){
     print("Enemy is close to player")
     enemy.update(playerPos: player.position)
}

checkCircularIntersection 函数仅检查玩家是否靠近敌人。

我的问题是敌人跟随玩家,但是当玩家移动时,敌人会移动到玩家之前站立的位置,然后停止一秒钟,然后再次移动到玩家站立的位置。但是玩家已经被移走了。
有没有办法让敌人永远跟随玩家,不停地避开障碍物?

【问题讨论】:

    标签: swift sprite-kit path-finding gameplay-kit


    【解决方案1】:

    您的代码专门防止在现有移动完成之前再次移动。

    guard !moving else { return }
    moving = true
    

    如果您想使用路径,则必须定期重新计算和重新应用路径移动以考虑目标的移动。

    但是,为了实现您的目标,Paths 并不是最适合使用的 GameKit 工具。 GKAgents 是专门为这种事情设计的。这将需要对您的代码进行重大重构,但请查看Agents, Goals and Behaviours

    【讨论】:

    • 我不明白为什么敌人的精灵要等一秒钟。计算路径的函数由 GameScene 的 update 方法调用。所以当敌人走完路径后,应该直接走新的路径,不用等待。还是寻路需要那么长时间才能找到一条新路径?不过谢谢提示!我将深入了解如何使用 GameplayKit。
    猜你喜欢
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多