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;
// read group's faces
foreach (var f in group.F)
{
// read face's vertices
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.
链接地址: http://www.djcxy.com/p/81844.html上一篇: 将四元数旋转转换为旋转矩阵?
下一篇: 在OpenGL中围绕它旋转对象