Webgl, Rotate object from different rotation origin?

Is there a way in P5.js to rotate an object by an origin other than 0,0.

For example, if I was making a human character, it it a way I would be able to rotate their arm from the shoulder joint instead of just the center of the object?

Sorry if I haven’t explained this very well,
Many thanks

1 Like
  1. p5js.org/reference/#/p5/push
  2. p5js.org/reference/#/p5/translate
  3. p5js.org/reference/#/p5/rotate
  4. p5js.org/reference/#/p5/pop

Thanks, I’m aware of how push/pop/rotate/etc work

I meant moreso if there was an inbuilt command that lets you rotate an object at a particular co-ordinate without having to rotate then translate?

Many thanks again

Hi @KeirMeDear, I’m sorry but I don’t think that exists in p5.js. I think the most relevant issue for this on GitHub is at https://github.com/processing/p5.js/issues/1534, in case you would like to see that context or comment that this would be useful for you. :purple_heart:

You first use translate then rotate

I usually put it in a function that I call from draw()

1 Like

One way is to create a rotateAround(x, y, r) function, as Chrisir suggestions, which does translate(x,y) + rotate(r). So: push, rotateAround, drawArm, pop.

The second way is to actually draw your arm around its hinge point – either as a draw routine like drawArm, or as a PShape or PGraphics. This is by far the easiest way – if your components are all centered around 0,0 hinge points, then you can just translate to the place on the body (the shoulder), then rotate (the angle of the arm) and draw, and the arm is always oriented and attached correctly.

So not:

rect(0,0,10,40);

but instead:

rect (-5,-5,10,40);

here is an example in processing Java and in 3D, using box instead of rect

float angleRightArm=0.0; 
float angleRightArmAdd=2; 

void setup() {
  size(1600, 900, P3D);
}

void draw() {
  background(255);
  lights(); 
  rightArm();
}

void rightArm() {
  // draw right arm

  pushMatrix(); // store matrix
  float armLength=300.0; 

  translate(255, 170, 0);  // arm position 
  rotateX(radians(angleRightArm));    // rotate  
  sphere();                // for testing only 
  translate(0, 0, armLength/2-20);  // that's the offset between arm center and where we want to have the shoulder / rotation !!!  

  // draw box/arm at 0,0,0 (box's center!) with the following width, height and depth: 
  fill(255); 
  stroke(0);
  box (15, 35, armLength);

  popMatrix();  // restore matrix

  // manage angle and angle bouncing:  
  angleRightArm += angleRightArmAdd;
  if (angleRightArm>12) {
    angleRightArmAdd=-2;
  }
  if (angleRightArm<-152) {
    angleRightArmAdd=2;
  }
}

void sphere() {

  // draw a sphere a the current 0,0,0 point

  fill(255, 0, 0);  // RED 
  noStroke();  
  sphere(11);
}
//