Processing, Rotate rectangle using matrix?

2019-08-27 08:49发布

问题:

I am trying to rotate a rectangle without using the rotate function, but instead using a matrix..I know how to rotate a line using a matrix but all my attempts to rotate a rectangle have failed.

I dont think this is use full but heres is my code that rotates the line.

float[][] rotation;
float[] position;
float theta = 180;
float pointX;
float pointY;
void setup() {

  frameRate(60);
  size(600, 600);

  pointX = 0;
  pointY = 0;

 rotation = new float[2][2];
 position = new float[8];
}

 void draw() {
 background(200);
 theta = mouseX;

 position[0] = mouseY;
 position[1] = mouseY;

 position[2] = -mouseY;
 position[3] = mouseY;

 rotation[0][0] = cos(radians(theta));
 rotation[0][1] = -sin(radians(theta));
 rotation[1][0] = sin(radians(theta));
 rotation[1][1] = cos(radians(theta));

 float newpos[] = new float[8]; 

 newpos[0] += position[0] * rotation[0][0];
 newpos[1] += position[1] * rotation[0][1];  

 translate(width/2, height/2);

 line(0, 0, pointX+newpos[0], pointY+newpos[1]);
 line(0, 0, pointX+newpos[0] * -1, pointY+newpos[1] * -1);

}

回答1:

Although the lines behaves properly it is by chance... You have a crucial part of the calculation of the new x and y of the point not as it should have been. As you can find in wikipedia, you need to calculate the sin and cos in the matrix as you properly did, but when creating the new point you don't exactly do this:



回答2:

Start by having a look at pushMatrix()/popMatrix() and coordinate spaces.

Have a look at Daniel Shiffman's tutorial as well, it's pretty well explained.

If you need to get lower level than this, have a look at the PMatrix2D class. Notice there is a rotate() function. After you rotate, you can either simply apply the matrix(using applyMatrix()) but you might as well be using push/pop matrix calls. Another option is multiply vectors(rectangle corners) to the rotation matrix and draw the result/transformed points.