Search code examples
c++openglrotationglm-math

Rotating child object in OpenGL c++


I'm adding a robot with multiple DoG to my OpenGL application(later i want to implement inverse kinematics for this robot) and i need to move objects that are "connected" together.

So far i added 3 STL object into scene and it looks like this

There is base, joint1 and joint2.

Base is stationary, joint1 and joint2 are for now rotating around Z axis based on keyboard input, but they both just rotate around theirs origin point, which is fine for joint1, but for joint2 i need them to be connected and translate accordingly.

Here is the output after rotation.

For object positioning and rotating i'm using regular MVP matrix and glm.

joint1M = glm::translate(joint1M, glm::vec3(-50.0f, -10.4f, 0.0f));
joint1M = glm::rotate(joint1M, glm::radians(rotation), glm::vec3(0.0f, 1.0f, 0.0f));
joint2M = glm::translate(joint2M, glm::vec3(-50.0f, 2.85f, 0.0f));
joint2M = glm::rotate(joint2M, glm::radians(rotation), glm::vec3(0.0f, 1.0f, 0.0f));

Is there any way to create something like child-parent Unity relationship in OpenGL? Or should i somehow change the position of joint2 based on joint1 rotation?


Solution

  • Thanks to the comments and more googling i managed to get this working like this:

    joint1 stays the same:

    joint1M = glm::translate(joint1M, glm::vec3(-50.0f, -10.4f, 0.0f));
    joint1M = glm::rotate(joint1M, glm::radians(rotation), glm::vec3(0.0f, 1.0f, 0.0f));
    

    joint2 moves to the position of joint1, rotates, moves where it's supposed to be

    joint2M = glm::translate(joint2M, glm::vec3(-50.0f, -10.4f, 0.0f));
    joint2M = glm::rotate(joint2M, glm::radians(rotation), glm::vec3(0.0f, 1.0f, 0.0f));
    joint2M = glm::translate(joint2M, glm::vec3(0.0f, 13.25f, 0.0f));