Hi i tried to perform matrix multiplication for 2d rotation.
I expected result that points will rotate in place, but instead i got flicker and movement outside screen.
Here is the source code:
float angle=10;
PVector[] points = new PVector[4];
float[][] rotationXY = {
{cos(angle),-sin(angle)},
{sin(angle),cos(angle)}
};
void setup(){
size(800,600);
frameRate(60);
int x=width/2,y=height/2,w=60,h=30;
points[0]=new PVector(x,y);
points[1]=new PVector(x+w,y);
points[2]=new PVector(x+w,y+h);
points[3]=new PVector(x,y+h);
}
void drawPoints(PVector[] point,color col){
strokeWeight(10);
stroke(col);
for(PVector v : point){
point(v.x,v.y);
}
}
void draw(){
background(0);
connect();
for(int i=0;i<points.length;i++)points[i]=pos(points[i]);
drawPoints(points,color(255));
}
void keyPressed(){
if(key == 'd')angle+=1;
if(key == 'a')angle-=1;
}
PVector pos(PVector pins){
float[][] result;
float[][] poins={
{pins.x},
{pins.y}
};
result = matmul(rotationXY,poins);
PVector ret = new PVector(result[0][0],result[1][0]);
return ret;
}
float[][] matmul(float[][] a, float[][] b){
int colsA = a[0].length;
int rowsA = a.length;
int colsB = b[0].length;
int rowsB = b.length;
if(colsA != rowsB){
println("collumns of A must match rows of B");
return null;
}
float result[][] = new float[rowsA][colsB];
for(int i=0;i<rowsA; i++){
for (int j=0;j<colsB;j++){
float sum=0;
for(int k = 0;k<rowsB;k++){
sum += a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
return result;
}
void connect(){
strokeWeight(3);
line(points[0].x,points[0].y,points[1].x,points[1].y);
line(points[1].x,points[1].y,points[2].x,points[2].y);
line(points[2].x,points[2].y,points[3].x,points[3].y);
line(points[3].x,points[3].y,points[0].x,points[0].y);
}
Please help.