Processing.js: 使用 ease out 停止加速

Processing.js: Stop acceleration using ease out

我正在查看代码本质中的示例。

具体例子有一个球加速朝向光标。但是,它到达了它并没有停下来,实际上它具有最大的动量,一旦超过它就开始减速,向光标加速,再次超过它。

我的问题是,如何让球加速,然后在它接触光标之前使用诸如缓出之类的过渡开始减速,以便它在接触光标之前停止?

ProcessingJS代码:

// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com

// A Mover object
Mover mover;

void setup() {
  size(640,360);
  mover = new Mover(); 
}

void draw() {
  background(255);

  // Update the position
  mover.update();
  // Display the Mover
  mover.display(); 
}

// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com

class Mover {

  // The Mover tracks position, velocity, and acceleration 
  PVector position;
  PVector velocity;
  PVector acceleration;
  // The Mover's maximum speed
  float topspeed;

  Mover() {
    // Start in the center
    position = new PVector(width/2,height/2);
    velocity = new PVector(0,0);
    topspeed = 5;
  }

  void update() {

    // Compute a vector that points from position to mouse
    PVector mouse = new PVector(mouseX,mouseY);
    PVector acceleration = PVector.sub(mouse,position);
    // Set magnitude of acceleration
    acceleration.setMag(0.2);

    // Velocity changes according to acceleration
    velocity.add(acceleration);
    // Limit the velocity by topspeed
    velocity.limit(topspeed);
    // position changes by velocity
    position.add(velocity);
  }

  void display() {
    stroke(0);
    strokeWeight(2);
    fill(127);
    ellipse(position.x,position.y,48,48);
  }

}

The Nature of Code 是一本很棒的书,我经常回来阅读它,尤其是在涉及自治代理时。

关于您的具体问题,希夫曼在同一章中进一步处理了这个确切的问题。 Take a look at example 6.2 on this page 你会得到你刚才描述的近似行为。 post 整个事情有点太长了,但这里有一个摘录,以防将来网站出现故障并且有人读到这个问题:

void arrive(PVector target) {
    PVector desired = PVector.sub(target,location);

    // The distance is the magnitude of
    // the vector pointing from
    // location to target.
    float d = desired.mag();
    desired.normalize();
    // If we are closer than 100 pixels...
    if (d < 100) {
      //[full] ...set the magnitude
      // according to how close we are.
      float m = map(d,0,100,0,maxspeed);
      desired.mult(m);
      //[end]
    } else {
      // Otherwise, proceed at maximum speed.
      desired.mult(maxspeed);
    }

    // The usual steering = desired - velocity
    PVector steer = PVector.sub(desired,velocity);
    steer.limit(maxforce);
    applyForce(steer);
  }

我不能相信代码,因为它是 Shiffman 的作品。我只是使者。玩得开心,感谢荣耀点数!