- Home /
Rotate an object based on vectors.
So I made several heads with the same mesh in blender but with different orientations. When I import them, their orientations are unfortunately set as is. (I don't want to change this)
Using vectors, I know the vector that goes from the center of the head to the top of the head.
I now want to rotate my head so that this vector now points to the top, how can I code this.
This is the code I tried so far.
Quaternion rotateUpDown = Quaternion.FromToRotation(solution1, Vector3.up);
for (int j = 0; j < verts.Length; j++)
{
verts[j] = rotateUpDown * verts[j];
//verts includes all the verticies of my mesh.
// I just rotate the mesh because I want to keep the orientation of my object.
}
Answer by rageingnonsense · Jul 14, 2017 at 06:51 PM
I believe you what you need is located here:
https://docs.unity3d.com/ScriptReference/Matrix4x4.TRS.html
The documentation has a good example for doing what you want. You should be able to tweak the code from there there.
But, just to go a little deeper; you don't want to think of this as "rotating vertices". You want to think of it more like "rotate the entire coordinate system of the vertices". In other words; if you had these points on a piece of graph paper, think of it as rotating the entire graph; not just re-drawing the points. This is what matrix multiplication will accomplish.
The code sample provided in that documentation will create a quaternion from eulerAngles, generate a matrix from it, and then multiply each vertex of the mesh by this matrix to "rotate" it.
I ended up using matrices and just doing all the calculations out but this method is much cleaner. Thanks a lot.