I would like to:
- translate, invert and rotate a single quadrilateral (PShape object) multiple times
- then change the height of one of its 2 top vertices
so as the whole thing act as an articulated arm that can be bent either to the right or the left.
To be as clear as possible I've made some graphics.
I know that I can:
- translate the quadrilateral using
translate()
- flip (invert) it with
scale(1, -1)
- rotate it using the
atan2()
function
PROBLEM
When combining the 3 together I end up with this:
The angle of rotation seems correct but obviously there's something off with the translation (either on the X or Y axis) and I can't figure out what exactly.
I suspect a missing translation for the pivot, or an incorrect order of transformations (or maybe both).
I would really appreciate if someone could help me understand what I'm doing wrong and how to fix this problem.
int W = 40;
int H = 40;
int offset = 10;
float[] p0 = {-W/2, -H/2};
float[] p1 = {-W/2, H/2};
float[] p2 = {W/2, H/2};
float[] p3 = {W/2, -H/2 - offset};
PShape object;
void setup(){
size(600, 600, P2D);
smooth(8);
noFill();
}
void draw(){
background(255);
pushMatrix();
translate(width>>1, height>>1);
float angle = atan2(p3[1] - p0[1], p3[0] - p0[0]);
for (int i = 0; i < 6; i++){
int factor = (i % 2 == 0) ? 1 : -1;
//Height translation
translate(0, H*factor);
//Flip all quads except 1st one
if (i > 0){
scale(1, -1);
}
//Rotate once every 2 quads
if (i%2 == 1){
rotate(-angle*2);
}
object();
}
popMatrix();
}
void object() {
beginShape(QUADS);
vertex(p0[0], p0[1]);
vertex(p1[0], p1[1]);
vertex(p2[0], p2[1]);
vertex(p3[0], p3[1]);
endShape();
}