处理PVector旋转

时间:2013-10-18 19:39:09

标签: rotation processing

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

现在我有了这个代码,但是它没有旋转PVectors,只是根据旋转变量将它们放得更远。

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);
}

2 个答案:

答案 0 :(得分:1)

要旋转矢量,您需要像代码中一样使用sincos等触发函数。但是,你的方法并不是最好的。添加到每个更新的现有(x,y)坐标上并不可行,因为您必须添加的数字每次都在变化。只是为每次更新覆盖和计算新值更容易。给定角度的xy坐标由单位圆圈给出:

Unit Circle

因此,给定x的{​​{1}}因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()变量,并为数组中的每个点计算新的rotationx值。您可以通过将y更改为更大/更小/正/负数来更改旋转速度和方向。

答案 1 :(得分: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;

请参阅Rotate a point by an angle