Translate, Rotate, Draw. (More Pushing and Popping)
Experimenting a bit further with matrix co-ordinates, I realised that its quite easy to forget which order that you are supposed perform the order of things, so I (badly) drew an easy to follow diagram that shows me how to do it.
Step 1. The initial step, the matrix 0,0 co-ordinate starts at the top left hand corner of your window. If you are using more than one it is here that you will pushMatrix().
Step 2. The translation step, the matrix is moved along the x and y axis to your desired spot.
Step 3. The rotation, the matrix is rotated through the z axis.
Step 4. Drawing, you can now draw whatever you want on the matrix. It is here that you would call the popMatrix() if you needed to draw on another matrix.
This sketch uses the translate, rotate and push and pop matrix functions to rotate rectangles held in an ArrayList as the mouse hovers over them.
class Square { int x, y; int sideLength = 50; int pen = 1; int r = 120; Square() { x = (int)random(width-sideLength); y = (int)random(height-sideLength); } Square(int x1, int y1) { x=x1; y=y1; } void drawSquare() { strokeWeight(pen); fill(r,0,0); pushMatrix(); translate(x,y); rect(0,0,sideLength, sideLength); line(-sideLength/2,-sideLength/2,sideLength/2,sideLength/2); popMatrix(); } void drawRotatedSquare() { strokeWeight(pen); fill(r,255-r,r); pushMatrix(); translate(x,y); rotate(90*PI/180); rect(0,0,sideLength, sideLength); line(-sideLength/2,-sideLength/2,sideLength/2,sideLength/2); popMatrix(); } boolean mouseOver(int mx,int my) { if ( mx >= x-sideLength/2 && mx < x+sideLength/2) { if ( my >= y-sideLength/2 && my < y+sideLength/2) { return true; } else return false; } else return false; } } Square sq; ArrayList sqs = new ArrayList(); int rotCount = 0; void setup() { rectMode(CENTER); size(500,500); for (int y = 0; y<height-50; y+=100) { for (int x = 0; x < width-50; x+=100) { sq = new Square(x+50,y+50); sqs.add(sq); } } } void draw() { rotCount = 0; background(190,0,0); int listSize = (sqs.size()); Square s; for (int i = 0; i<listSize; i++) { s = (Square)sqs.get(i); if (s.mouseOver(mouseX,mouseY)) { s.pen = 6; s.r = (int)random(255); s.drawRotatedSquare(); } else { s.pen = 1; s.drawSquare(); } } }







