Rotating an object around a fixed point using glMultMatrix

前端 未结 3 566
说谎
说谎 2020-12-02 02:55

Rotating an object around (x,y,0) : //2D

glTranslatef(-x, -y, 0);
glRotatef(theta, 0.0, 0.0, 1.0); 
glTranslatef(x, y, 0);

is it correct?!

3条回答
  •  误落风尘
    2020-12-02 03:33

    Since none of the previous answers look entirely correct and complete, let me try:

    The key point to understand is that the transformations are applied to your vertices in reverse order of the order you specify them in. The last transformation you specify is the first one that is applied to your vertices.

    This applies both to using calls like glTranslate and glRotate, and to using glMultMatrix. glTranslate and glRotate are convenience functions to build specific types of transformations, but they operate just like glMultMatrix.

    In your example, to rotate around an arbitrary point, you need to first translate your vertices so that the rotation point moves to the origin, i.e. you want to translate by (-x, -y, 0). Then you apply the rotation. Then translate the origin back to the rotation point, which means a translation by (x, y, 0).

    Now, since we need to specify these steps in reverse order, this means that your initial set of transformations is in the wrong order. It needs to be:

    glTranslatef(x, y, 0);
    glRotatef(theta, 0.0, 0.0, 1.0); 
    glTranslatef(-x, -y, 0);
    

    Your version using glMultMatrix looks correct, since you're already specifying the transformations in this order.

提交回复
热议问题