为什么球不在 window 的中心?

why is the ball not in the center of the window?

代码:

class Attractor {

  PVector location;
  float mass;

  Attractor() {
    location = new PVector(width/2, height/2);
    mass = 5;
  }

  void display() {
    stroke(0);
    fill(125);
    ellipse(location.x, location.y, mass*10, mass*10);
  }
}

Attractor a = new Attractor();

void setup()
{
  size(640, 360);
}

void draw()
{
  background(255);
  a.display();
}

球的位置在Attractor对象中,即PVector(width/2,height/2).

所以我想知道为什么当我 运行 代码时,它不在中间而是在 window 的右侧和上方。

这是因为您在 调用 setup() 函数之前创建了 Attractor widthheight还没有设置,所以默认为100

要解决此问题,只需确保在调用 size() 函数后创建 Attractor

Attractor a;

void setup()
{
  size(640, 360);
  a = new Attractor();
}