我正在阅读这本书The Nature of Code,其中练习3.12要求我实施双摆。
class Pendulum {
PVector origin, location;
float r; // arm length
float angle;
float aVelocity;
float aAcceleration;
float damping;
Pendulum(PVector origin_, float r_) {
origin = origin_.get();
location = new PVector();
r = r_;
angle = PI/3;
aVelocity = 0;
aAcceleration = 0;
damping = 0.995;
}
void go() {
update();
display();
}
void update() {
float gravity = 0.4;
aAcceleration = (-1 * gravity / r) * sin(angle);
aVelocity += aAcceleration;
angle += aVelocity;
aVelocity *= damping;
location.set(r*sin(angle), r*cos(angle));
location.add(origin);
}
void display() {
stroke(0);
line(origin.x, origin.y, location.x, location.y);
fill(150);
ellipse(location.x, location.y, 20, 20);
}
}
Pendulum p, p2;
void setup() {
size(640, 360);
p = new Pendulum(new PVector(width/2, 0), 150);
p2 = new Pendulum(p.location, 100);
}
void draw() {
background(255);
p.go();
p2.go();
}
因此,在setup
函数中,我将origin
的{{1}}设置为p2
的{{1}},但location
为p1
出现在位置(0,0)上。那我该怎么办呢?我试图为origin
设置一个临时变量,但这并不方便。
答案 0 :(得分:2)
我不确定你要做什么, 但在构造函数中:
Pendulum(PVector origin_, float r_) {
origin = origin_.get();
location = new PVector(); <-- here you set the location to a new vector
...
}
您可以直接使用此处的位置:
void setup() {
size(640, 360);
p = new Pendulum(new PVector(width/2, 0), 150);
p2 = new Pendulum(p.location, 100); <-- here
}
这是创建的新位置。我认为这是你应该研究的问题。