Search code examples
c++transformglm-math

How to translate, rotate and scale at a particular point?


I want to translate, rotate and scale, all of these transformations from a specified point(origin). This is what I use right now(I tried many combinations but still cannot figure it out! Looks like it's back to learning Linear Algebra for me).

I am using GLM.

Take a look at the code which I am using:-

GLfloat rx = sprite->origin.x / width;
GLfloat ry = sprite->origin.y / height;

translate(model, vec3( -sprite->origin.x, -sprite->origin.y, 0.0f ));
translate(model, vec3( rx * scale[0], ry * scale[1], 0.0f ));
rotate(model, radians(rotation), vec3( 0.0f, 0.0f, 1.0f ));
translate(model, vec3( -(rx * scale[0]), -(ry * scale[1]), 0.0f ));
scale(model, vec3( width * scale[0], height * scale[1], 1.0f ));
translate(model, vec3( position[0], position[1], 0.0f ));

Origin is the starting point of the object, then translate it to the center for rotation and then translate back.

Scale it and translate the object to the specified position.

I mean, what is wrong with this code?


Solution

  • I found the answer,

    Do it in this order:-

    1. Translate the object to the position, e.g, vec3(position, 0.0f).

    2. And then rotate the object.

    3. Translate the point back to the origin, e.g, vec3(-originx * scale, -originy * scale, 0.0f).

    4. Finally, scale the object.


    Explanation:

    Take the position of the object as 0, 0 in 2D coordinates(take it as the variable position mentioned above in the example of the first point).

    You can see that the object will translate(move) to the position.

    Note: Don't forget to multiply it with your scale or it can yield wrong results if your scale is more than 1.

    Now is the time you rotate the object.

    Scaling works from the top-left corner so you can't do it from the center.

    Next, just scale the object.

    That's all.