处理.js:使用缓和停止加速



我正在看一个来自 Nature of Code 的例子。

具体的例子有一个球加速到光标。然而,当它到达它时,它并没有停止,实际上它具有最大的动量,一旦它通过它就开始减速,加速到光标,并再次超过它。

我的问题是,如何让球加速,然后在它接触光标之前使用缓出等过渡开始减速,这样它在接触光标之前就停止了?

处理JS代码:

// 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,你会得到你刚才描述的近似的举止。发布整个事情有点太长了,但这里有一段摘录,以防万一网站将来出现故障并且有人阅读了这个问题:

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写的。我只是信使。玩得开心,感谢荣耀积分!

最新更新