到达行为

2022-06-29  本文已影响0人  大龙10

书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
第6章目录

6.4 到达行为

1、改进

  上例中,在模拟小车寻找行为时,小车会超过目标位置,然后又回头继续寻找目标,最后往复运动。
  这是因为小车在寻找目标时过于兴奋,以至于它无法根据目标的距离确定合理的运动速度。无论目标是远是近,它始终以最大的速度运动。

  在某些场景中,这是我们想要的行为(比如,导弹在射击过程中,朝着目标运动的速度应当尽可能快)。
  但在另一些场景中(比如泊车,或者模拟蜜蜂停在花朵上),小车应该改变思维方式,在计算运动速度时应该考虑目标的距离。

2、如何实现

  如何用代码实现“到达”行为?回到seek()函数的实现,我们用一行代码设置了所需速度的大小。

PVector desired = PVector.sub(target,location);
desired.normalize();
desired.mult(maxspeed);
PVector desired = PVector.sub(target,location);
desired.div(2);
PVector desired = PVector.sub(target,location);
desired.mult(0.05);

3、更好的方法

4、转向力的本质

5、示例

示例代码6-2 到达转向行为

  // A method that calculates a steering force towards a target
  // STEER = DESIRED MINUS VELOCITY
  void arrive(PVector target) {
    PVector desired = PVector.sub(target,position);  // A vector pointing from the position to the target
    float d = desired.mag();
    // Scale with arbitrary damping within 100 pixels
    if (d < 100) {
      float m = map(d,0,100,0,maxspeed);
      desired.setMag(m);
    } else {
      desired.setMag(maxspeed);
    }
    // Steering = Desired minus Velocity
    PVector steer = PVector.sub(desired,velocity);
    steer.limit(maxforce);  // Limit to maximum steering force
    applyForce(steer);
  }

6、结果

上一篇 下一篇

猜你喜欢

热点阅读