0

问题是我在中间的主 PVector 周围放置了一组 PVector。我希望我的 PVector 数组基于旋转变量围绕我的主 PVector 旋转。有没有办法做到这一点?

现在我有这个代码,但它不会旋转 PVector,只是根据旋转变量将它们放在更远的地方。

class Box {
  PVector location;
  PVector[] points;
  float rotation = random(360);
  Box() {
    location = new PVector(random(width), random(height));
    points = new PVector[4];

    for(a = 0; a < points.length; a ++) {
      points[a] = new PVector(0,0); 
    }
  }

  void update() {
    points[0].x = location.x + 10 * sin(rotation);
    points[0].y = location.y + 10 * sin(rotation);

    points[1].x = location.x + 10 * sin(rotation);
    points[1].y = location.y - 10 * sin(rotation);

    points[2].x = location.x - 10 * sin(rotation);
    points[2].y = location.y + 10 * sin(rotation);

    points[3].x = location.x - 10 * sin(rotation);
    points[3].y = location.y - 10 * sin(rotation);
}
4

2 回答 2

1

要旋转向量,您确实需要使用sincos代码中类似的三角函数。但是,您的方法并不是最好的。在每次更新时添加到现有的 (x,y) 坐标上实际上并不可行,因为您必须添加的数字每次都在变化。为每次更新覆盖和计算新值更容易。给定角度的x和坐标由单位圆给出:y

单位圆

因此,x给定的PVector随 而变化,cos(theta)y随 而变化sin(theta)。检查以下代码:

Box b;

void setup(){
  size(300,300);
  b = new Box();
}
void draw(){
  background(255);
  b.update(mouseX, mouseY);
  b.display();
}

class Box {
  PVector location;
  PVector[] points;
  float rotation;
  float radius;
  Box() {
    location = new PVector(width/2,height/2);
    points = new PVector[7];
    rotation = 0;
    radius = 50;
    for(int i = 0; i < points.length; i ++) {
      //this centers the points around (0,0), so you need to add in
      //the box coordinates later on.
      points[i] = new PVector(radius*cos(rotation + i*TWO_PI/points.length),
                              radius*sin(rotation + i*TWO_PI/points.length)); 
    }
  }
  void update(int x, int y) {
    location.set(x,y);
    rotation += 0.08; // change for different rotation speeds.
    for(int i = 0; i < points.length; i++){
      points[i].set(radius*cos(rotation + i*TWO_PI/points.length),
                    radius*sin(rotation + i*TWO_PI/points.length)); 
    }
  }
  void display(){
    stroke(0);
    for(int i = 0; i < points.length; i++){
      //points are treated as offsets from the center point:
      line(location.x,location.y,location.x+points[i].x,location.y+points[i].y);
      ellipse(location.x+points[i].x,location.y+points[i].y,10,10);
    }
  }
}

对于每次update()调用,它都会增加rotation变量并计算数组中每个点的新值xy值。您可以通过更改0.08为更大/更小/正/负数来更改旋转速度和方向。

于 2013-10-19T05:35:02.570 回答
0

要围绕位置旋转一个点:

double x = cos(rotation) * (point.x-location.x) - sin(rotation) * (point.y-location.y) + location.x;
double y = sin(rotation) * (point.x-location.x) + cos(rotation) * (point.y-location.y) + location.y;
point.x = x;
point.y = y;

请参见按角度旋转点

于 2013-10-19T05:36:24.267 回答