Rotating round Z axis but not at origin

This may be a stupid question but I am quite new to OpenGL.

Basically I have an X variable (Xcoord) and a Y variable (Ycoord) and I am making a game in which I want the main character to face the direction that is been pressed. I won’t post all the code as most of it works it is just the end bit that I can’t get to work:

while (Q < P)
{
	glRotatef(45, Xcoord, Ycoord, 1);
	Q = Q+1;
}

P is how many times a rotation of 45 degrees is needed to face the right direction and Q is set to 0. I want it to just rotate around the Z axis but at point Xcoord, Ycoord, 0. Anyone know how I could do this? Also the characters position isn’t calculated using translations so I can’t rotate him first.

The last 3 params of glrotate define the rotation axis. In your case “around Z axis” means 0,0,1.
To rotate the character you need to pre-translate it (gl translate command done after the rotate due to the matrix multiplication order):

glRotatef(45 * P, 0, 0, 1);
glTranslatef(-Xcoord, -Ycoord,0);

I could be misunderstanding the original request, but wouldn’t the actual sequence of calls be:

glTranslatef(Xcooord, Ycoord, 0);
glRotatef(45 * P, 0, 0, 1);

According to the OpenGL redbook a way to look at this problem is as a change in coordinate systems-- and when you think of it that way the order of operations takes place in the same order as the API calls.

So in the above we first move the coordinate system to the appropriate location via glTranslate(). Then we rotate it about the newly relocated coordinate system’s local Z axis.

Any subsequent glVertex() calls will then be “spun” around this rotated Z axis, which I believe is what he’s looking for.

Random89, can you let us know if this works for you, or if ZbuffeR’s technique is what you’re actually after?

The problem with moving the axis with the main character is that I have a lot of other stuff rendered and randomly moving which means if I move the coordinate system all the other stuff will move as well. Or is there some way to change the coordinate system just for a short time (for example until I pop the current matrix)?

Sure.
glPushMatrix();
…translate/rotate whatever…
… draw stuff…
glPopMatrix();
// back to normal

I have half got it working, I move the character to the origin and then rotate and then move him back to his original position. Had to use some interesting maths but it sort of works. Probably not the easiest way though.