Sunday, November 29, 2009

OpenGL glRotatef

While working on a recent project, ive' decided that i wanted to give the user freedom to rotate the object about its' axis and see what it looks like. Sounds fair enough right.. i mean its' a 3d object.. so let the user view it as he wants to.... so i started coding.. now i wanted the user to be able to rotate the object on Global X axis and the Global Y axis. So i have two different angles one about X and one about Y. How do i rotate them correctly so that i produce the right rotation? (in opengl) The problem here is once you rotate about an axis, the co-ordinate system is changed and you have to figure out how to rotate around the other axis. Here is the thing.. glRotatef() actually takes in an "angle" and "vector" about which the rotation should happen. I have convinently forgotten this information and struggled to find the answer... .some where in the forums some one mentioned .. its' an arbitrary vector you can rotate about.. wel.. that fixed my problem. .. so here is the sequence of calls you make ...

glPushMatrix();
glTranslatef(objCenterX, ObjCenterY, ObjCenterZ);

//rotate about y axis now the x axis is changed.
glRotatef(angle[0], 0, 1, 0);
//the new globalX axis is cos(angle[0] *pi/180), 0, sin(angle[0] * pi/180)
glRotatef(angle[1], cos(angle[0] * pi/180), 0, sin(angle[0]*pi/180));
glTranslatef(-objCenterX, -ObjCenterY, -ObjCenterZ);
... //draw the object
glPopMatrix();
This was particularly exciting to me because.. i knew glRotatef function takes a vector.. but i just couldn't figure out how to use it till i saw somebody post it in as a solution to the problem i mentioned above.
Just in case you are interested in looking at the conversation that helped me figure out the solution.. here you go
Post a Comment