为什么第二个球的原点不附在第一个球上?

Why does the origin of the second ball not attached to the first ball?

我正在阅读书 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函数中,我将p2origin设置为p1location。但是,p2origin出现在(0, 0)位置。我应该如何解决这个问题?我试图为 p2 设置一个临时变量,但这并不方便。

我不太确定你想做什么, 但在构造函数中:

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
}

这是创建的新位置。我想这是你应该调查的问题。