GameplayKit>使代理停止移动,追踪目标

我正在做一个代理跟踪一个GKPath,将其行为添加到下面的目标:GKPath。 一切工作正常,但代理人继续移动时,在达到path上的目标点8样。 如何防止代理在到达GKPath上的目标点时漫游?

我已经考虑过的一个解决scheme是设置另一个目标:当接近目标点时,达到目标速度:0.0。 但是,我不确定最好的做法是什么,因为没有build立目标何时“完成”。

  1. 我是否使用IF语句来检查每次更新时的目标距离:? 性能呢?
  2. 我使用某种GKRule吗?

您的build议将非常感激。 谢谢。

我去了第一个选项,即跟踪运动组件更新函数中的目标距离:

override func update(deltaTime seconds: TimeInterval) { guard let entity = self.entity as? BaseEntity else { return } if entity.moving { let targetPoint = CGPoint(x: 100, y: 100) let distanceToTarget = distanceFrom(point: point) if distanceToTarget < GameConfiguration.Movement.targetProximity { stopMovement(afterTraversing: distanceToTarget) } } } func distanceFrom(point: CGPoint) -> Float { guard let entity = self.entity as? BaseEntity else { return CGFloat.greatestFiniteMagnitude } let dx = point.x - entity.visualComponent.node.position.x let dy = point.y - entity.visualComponent.node.position.y return hypotf(Float(dx), Float(dy)) } 

当代理与目标足够接近时,运行stopMovement函数。 反过来,这将计算所需的时间,以遍历左侧的目标(具有恒定的速度),并将把时间强制停止代理:

 func stopMovement(afterTraversing distance: Float) { guard let entity = self.entity as? BaseEntity else { return } guard (entity.moving) else { return } guard let behavior = entity.agent.behavior as? MovingBehavior else { return } let timeToTarget = TimeInterval(distance / entity.agent.maxSpeed) Timer.scheduledTimer(withTimeInterval: timeToTarget, repeats: false, block: {_ in behavior.stopMoving() entity.agent.maxSpeed = 0.0 entity.moving = false }) } class MovingBehavior: GKBehavior { var reachMaxSpeed: GKGoal var followPathGoal: GKGoal var stopMovingGoal = GKGoal(toReachTargetSpeed: 0.0) init(path: GKPath, target: GKGraphNode, maxSpeed: Float) { reachMaxSpeed = GKGoal(toReachTargetSpeed: maxSpeed) followPathGoal = GKGoal(toFollow: path, maxPredictionTime: 1.0, forward: true) super.init() setWeight(1.0, for: reachMaxSpeed) setWeight(0.8, for: followPathGoal) setWeight(0.0, for: stopMovingGoal) } func stopMoving() { setWeight(0.0, for: reachMaxSpeed) setWeight(0.0, for: followPathGoal) setWeight(1.0, for: stopMovingGoal) } }