# Rotating an object around it's centre in OpenGL

I'm writing small 3d viewer of models from .obj file.
I have a car and I want to rotate car's wheels. I found a lot of good examples but I still have a problem: wheel rotates around point at the it's border, not around center. You can see it on the gif.
Below part of code without code for material and lighting. I find coordinates of wheel's center.

GL.PushMatrix();

// Rotate the car
GL.Translate(x, y, z); //x=0, y=0, z=0
GL.Rotate(ori, 0, 1, 0); // ori=90

// ...
// Material and lighting code
// ...

foreach (var group in file.G)
{
GL.PushMatrix();
if (group.name == "wheel_rf")
{
float xTmp, yTmp, zTmp;
xTmp = yTmp = zTmp = 0;
int count = 0;
foreach (var f in group.F)
{
foreach (var v in f.V)
{
yTmp += v.Y;
zTmp += v.Z;
xTmp += v.X;
count++;
}
}
yTmp /= count;
zTmp /= count;
xTmp /= count;
GL.Translate(xTmp, yTmp, zTmp);
GL.Rotate(this.wheelAngle, 1, 0, 0);
GL.Translate(-xTmp, -yTmp, -zTmp);
}

// draw faces for each group
GL.Begin(file.PrimitiveType);
foreach (var face in group.F)
{
GL.TexCoord2(face.VT[0]);
GL.Normal3(face.VN[0]);
GL.Vertex3(face.V[0]);

GL.TexCoord2(face.VT[1]);
GL.Normal3(face.VN[1]);
GL.Vertex3(face.V[1]);

GL.TexCoord2(face.VT[2]);
GL.Normal3(face.VN[2]);
GL.Vertex3(face.V[2]);
}
GL.End();
GL.PopMatrix();
}
GL.PopMatrix();


Note! In first time I rotate all car on 90 degrees otherwise I would have seen the car back. I can't find reason of problem. Maybe trouble in the car model, but whole car is drawn fine.

• It looks like your xTmp/yTmp/zTmp is the "origin" of the wheel, you should add half of the bounding box on each axis of the wheel to get the center. This center may not be exact if you need it also for say, turning the steering. You could also modify the mesh vertices in the model, to make the vertices origin in the center. This is often called the "pivot", but you can just offset the vertices in a model editor or even in the code to add an additional origin offset when translating. – underscorediscovery Dec 15 '16 at 18:48
• Am I right in thinking xTmp/yTmp/zTmp is the average of the vertex positions in the wheel? (so hopefully the centre of the wheel, if the wheel is symmetrical) – user253751 Dec 18 '16 at 22:35
• In that case you might try swapping the two translate calls. – user253751 Dec 19 '16 at 2:27