【问题标题】:Processing.js: Stop acceleration using ease out [closed]Processing.js:使用缓出停止加速[关闭]
【发布时间】:2019-12-07 22:45:44
【问题描述】:

我正在查看 Nature of Code 中的一个示例。

这个特定的例子有一个球向光标加速。但是,它到达它并没有停止,实际上它具有最大的动量,一旦经过它就开始减速,向光标加速,然后再次越过它。

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

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

}

【问题讨论】:

  • 很好的问题,虽然我觉得在这里作弊,因为 Shiffman 在同一章稍后回答了它。
  • 看看例子6.2。
  • 嘿@laancelot 发表您的最后一条评论,并附上链接作为获得荣耀+积分的答案。
  • 如果这本书已经回答了这个问题,那么与其发布答案,任何阅读 Shiffman 的书的人都会自己找到答案,而这个问题不应该一直存在。

标签: processing game-physics physics processing.js


【解决方案1】:

《代码的本质》是一本很棒的书,我经常回来阅读它,尤其是在涉及自主代理时。

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

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 的作品。我只是一个使者。玩得开心,感谢您的荣耀积分!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-09
    • 2016-10-28
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    相关资源
    最近更新 更多