//Program will draw a single random point triangle and rotate it
//multiple times in increments of .25*PI radians.
int screenwid = 720;
int screenhei = 480;
float[][] rotation = new float[2][2];

void setup() {
size(screenwid, screenhei);
noLoop();
}

void draw() {
//Create a random triangle
int x0, y0, x1, y1, x2, y2;
x0 = int(random(screenwid));
y0 = int(random(screenhei));
x1 = int(random(screenwid));
y1 = int(random(screenhei));
x2 = int(random(screenwid));
y2 = int(random(screenhei));
//Rotate it in increments of .25*PI radians
for(float i = 0; i < 2; i += .25) {
rotation(x0, y0, x1, y1, x2, y2, (i*PI));
}
}

void rotation(int x0, int y0, int x1, int y1, int x2, int y2, float rotat) {
//Set rotation angle
setRotation(rotat);
//Calculate origin of desired triangle
int origx = int((x0+x1+x2)/3);
int origy = int((y0+y1+y2)/3);
//Create point matrix based on origin
float[][] points = {{x0-origx, y0-origy}, {x1-origx, y1-origy}, {x2-origx, y2-origy}};
//Multiply by rotation matrix
points = multiply(points, rotation);
//Add back origin
for(int i = 0; i < points.length; i++) {
for(int j = 0; j < points[0].length; j++) {
if(j == 0)
points[i][j] += origx;
else
points[i][j] += origy;
}
}
//Show rotated triangle
triangle(points[0][0], points[0][1], points[1][0], points[1][1], points[2][0], points[2][1]);
}

//Sets the values of the rotation matrix
void setRotation(float rotat) {
rotation[0][0] = cos(rotat);
rotation[0][1] = sin(rotat);
rotation[1][0] = -sin(rotat);
rotation[1][1] = cos(rotat);
}

//Used to multiply one matrix to another
float[][] multiply(float[][] a, float[][] b) {
float[][] c = new float[a.length][b[0].length];
for(int i = 0; i < c.length; i++) {
for(int j = 0; j < c[0].length; j++) {
for(int k = 0; k < b.length; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
return c;
}

0 comments: