KayMK11
KayMK11

Reputation: 107

How do I rotate an object, with another object as pivot

Say I have object A and object B, I have control of A's movement and rotation.

I'm trying to link A and B together in such way, that when A moves, relative distance b/w A and B remains same. and when A rotates by an angle, B also rotates with the same angle, but its rotation pivot as position of A.

you can imagine it like you (A) being connected to your phone (B) with a selfie stick.

enter image description here

I've been trying to figure out what Matrix operations will be required, to make this possible.

I've been told this looks like parent child relation b/w 2 objects, therefore I can use ModelMatrix of the parent (A in this case) and apply local transformation Matrix to get Model Matrix of child (B in this case).

In practice, it only fixed the relative position b/w the 2 object, but for rotation it didn't work

Upvotes: 1

Views: 784

Answers (1)

Rabbid76
Rabbid76

Reputation: 211077

If you want to rotate around a pivot you have to:

  • Translate the object so that the pivot point is moved to (0, 0).
  • Rotate the object.
  • Move the object so that the pivot point moves in its original position.
glm::vec3 pivot(object_A_x, object_A_y, object_A_z);
glm::vec3 rotation_axis(0.0f, 0.0f, 1.0f)
float angle_rad = glm::radians(rotation_angle_degree)

glm::mat4 translate_to_orgin = glm::translate(glm::mat4(1.0f), -pivot);
glm::mat4 rotate             = glm::rotate(glm::mat4(1.0f), angle_rad, rotation_axis);
glm::mat4 translate_back     = glm::translate(glm::mat4(1.0f), pivot);

glm mat4 rotate_around_pivot = translate_back * rotate * translate_to_orgin;

Upvotes: 1

Related Questions