创建第二个对象会使 class 的功能不再起作用

Creating a second object makes functions of class not work anymore

我正在尝试编写一个显示矢量的 class。如果我创建一个矢量对象,一切都会按预期进行。在我的示例代码中,对象 lin1 是在 draw() 函数的帮助下绘制的。

如果我现在创建第二个矢量对象,(未更改的)绘制函数将不再执行任何操作,即使对象本身没有更改。反之亦然:如果第二个对象是唯一存在的,则可以绘制,但前提是lin1不存在。

有谁知道我的错误在哪里?

vector lin;
vector lin2;

void setup()
{
  size(500,500);
  background(255);
  cenX = width/2;
  cenY = height/2;
  noLoop();
}

void draw()
{
  coordSys();
  lin = new vector(0,0,100,100);
  lin2 = new vector(0,0,-200,-200);
  lin.draw();
  lin2.draw();
  lin.getAll();
}

class vector
{
  float x1,y1,x2,y2;
  float length;
  float angle;
  float gegenK, anK;

  vector(float nx1, float ny1, float nx2, float ny2)
  {
    translate(cenX,cenY);
    x1 = nx1; y1 = -ny1; x2 = nx2; y2 = -ny2; 
    strokeWeight(2);
    // Gegenkathete
    gegenK = ny2 - ny1;
    // Ankathete
    anK = x2 - x1;
    // length and angle
    length = sqrt(sq(anK) + sq(gegenK));
    angle = winkel(gegenK, anK);
  }

  void draw()
  {
    stroke(0);
    line(x1,y1,x2,y2);
  }
}
}

编写代码时请使用标准命名约定。具体来说,你的 class 应该是 Vector 和一个大写的 V。另外,请 post 你的代码以 MCVE 的形式编译和运行。

无论如何,Vector() 构造函数中的第一个调用是这样的:

translate(cenX,cenY);

这会将 window 的原点移动到 window 的一半。当您这样做一次时,这只会使您的绘图调用相对于 window 的中心。但是当你这样做两次时,它会将原点移动到 window 的右下角,因此你所有的绘图都会移出屏幕边缘。

要解决您的问题,您需要移动这条线,使其只发生一次(可能在 draw() 函数的开头)而不是每次绘制 Vector。解决这个问题的另一种方法是使用 pushMatrix()popMatrix() 函数来避免这种 window 翻译的堆叠。