PDA

View Full Version : Rotating an object around it's centre



bildeyko
12-15-2016, 02:39 AM
I'm writing small 3d viewer of models from .obj file. I use c# and OpenTK
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 picture (sorry, i have a gif but a can't attach it).
2305

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.

OceanJeff40
12-15-2016, 07:25 PM
You could take all the coordinates and run them through a function to find the furthest X,Y and Z coordinates, then take the average of each, and there's your center to rotate around.

Does that help?

I'm playing around with rotation tonight too, but only 2D. I'll let you know if I find anything more useful. Also, perhaps look at the rotate function you are calling, maybe it has some parameters so you can specify which point to rotate the object around.

Jeff

GClements
12-15-2016, 07:59 PM
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);
}


Note that this rotates about the wheel's centroid, which isn't necessarily its centre. If the wheel has rotational symmetry, then the centroid will be the centre, but if there's any asymmetry it will affect the centroid. Subdivision of polygons or complex regions into triangles can cause this.

Alternatives include using the centre of the bounding box, or averaging the centroids of triangles weighted by the area of the triangle (the latter results in subdivided areas having the same centroid regardless of how they're subdivided).