【发布时间】: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