# Rotating rectangles to face mouseX, mouseY

Hi everyone! I’ve taken a few years out from using processing so I’m sorry if I’m missing something pretty basic!

I’m trying to individually rotate each rectangle generated from a nested for loop to face the mouse coordinates - but at the moment each rectangle is rotating as a group. The rotation isn’t right yet either but I’m more concerned that they are rotating in unison for now… does anyone have any advice for getting them to act independently?

Thanks!

``````void setup() {
pixelDensity(displayDensity());
size(1000, 500);
background(0);
colorMode(HSB, 100);
fill(0, 70, 70);
rectMode(CENTER);
}

int totalRows = 5;
int totalColumns = 5;

void draw() {
background(0);
for (int row = 1; row <= totalRows; row++) {
for (int column = 1; column <= totalColumns; column++) {

float x1 = column * (width * 0.8 / totalColumns) + (0.05 * width); //set the center points of the rectangles
float y1 = row * (height * 0.8 / totalRows) + (0.05 * height); //set the center points of the rectangles

pushMatrix();
translate(x1, y1); //go to center point
float mX = mouseX + 1; //set to floats to allow division, + 1 to avoid division by 0 errors
float mY = mouseY + 1; //set to floats to allow division, + 1 to avoid division by 0 errors
rotate(atan((mY/(mX)))); //arctan of mouse coordiantes, considering rectangle center is now at (0,0) due to translation.
rect(0, 0, width*0.05, height*0.01, width*0.005);
popMatrix();
}
}
}
``````
1 Like

I thought it might be helpful to show what I’m trying to achieve - here’s a rough illustration!

1 Like

Hello,

Try:

``````rotate(atan2(y1-mY, x1-mX));
``````

See the reference:
https://processing.org/reference/atan2_.html

`:) `

2 Likes

Amazing thank you so much!

2 Likes