Find "real" rotation of box mesh
Hi all. I'm trying to create editor extension to automatically create BoxColliders for box meshes. In Unity editor box colliders can only be aligned by axis but in 'real world' meshes are often rotated in 3d modelling application so their transform.rotation is 0,0,0. To workaround this I creating child empty game object and attaching BoxCollider to it. Then empty game object can be rotated to get the same 'real' rotation as its parent. I created a script which used tringles and vertices data of the mesh and seems to be worked in simple cases but not accurate when mesh rotated in all 3 dimensions simultaneously. As you can see rotation of collider not the same as rotation of the mesh.
And code of the method below:
private void CreateBoxCollider(Vector3[] Vertices, int[] Triangles, BoxCollider Collider)
{
List<Vector3> edges = new List<Vector3>()
{
Vertices[Triangles[0]]- Vertices[Triangles[1]],
Vertices[Triangles[2]]- Vertices[Triangles[1]],
FindPerpendicularToFirstTriangle(Vertices, Triangles)-Vertices[Triangles[1]]
};
//Find longest edge by x
Vector3 xEdge = edges.Aggregate((l1, l2) => Mathf.Abs(l1.x) > Mathf.Abs(l2.x) ? l1 : l2);
edges.Remove(xEdge);
//Find longest edge by z
Vector3 zEdge = edges.Aggregate((l1, l2) => Mathf.Abs(l1.z) > Mathf.Abs(l2.z) ? l1 : l2);
edges.Remove(zEdge);
Vector3 yEdge = edges.First();
Collider.size = new Vector3(xEdge.magnitude, yEdge.magnitude, zEdge.magnitude);
//Find angle between xEdge and X axis to get rotation around Y
float yRotation = Math3d.SignedAngle(Vector3.right, new Vector3(xEdge.x, 0, xEdge.z));
//Find angle between zEdge and Z axis to get rotation around X
float xRotation = Math3d.SignedAngle(Vector3.forward, new Vector3(0, zEdge.y, zEdge.z));
//Find angle between yEdge and Y axis to get rotation around Z
float zRotation = Math3d.SignedAngle(Vector3.up, new Vector3(yEdge.x, yEdge.y, 0));
Collider.transform.Rotate(xRotation, yRotation, zRotation);
}
private static float SignedAngle(Vector3 a, Vector3 b)
{
float angle = Vector3.Angle(a, b);
return angle * Mathf.Sign(Vector3.Cross(a, b).y);
}
I understand that I'm missing something trivial where rotation around one axis affects rotation around other axis and I have to take this into account when measuring angles between mesh edges and axis. But I don't understand how I should modify these angles to get accurate rotation. Is anyone can point me to the right direction? Any help will be appreciated.
Thanks in advance.
Your answer
Follow this Question
Related Questions
How to calculate correct angles for PID? 0 Answers
Rotating a camera around a game object? 2 Answers
Intersection of a Plane and an object 0 Answers
Finding Touching Faces Based on Rotation for Cubes in 3D 1 Answer
Find direction on a sphere? 1 Answer