What I am looking for is the most efficient way to get the world position of the 8 vertices of the Box Collider of a freely rotated Game Object. I cannot use collider.bounds since object is rotated, not axis-aligned.
I'm using Unity 5 with C#.
What I am looking for is the most efficient way to get the world position of the 8 vertices of the Box Collider of a freely rotated Game Object. I cannot use collider.bounds since object is rotated, not axis-aligned.
I'm using Unity 5 with C#.
Try this:
BoxCollider b = obj.GetComponent<BoxCollider>(); //retrieves the Box Collider of the GameObject called obj
Vector3 vertice1 = myobject.transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, -b.size.z)*0.5f);
Vector3 vertice2 = myobject.transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, -b.size.z)*0.5f);
Vector3 vertice3 = myobject.transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, b.size.z)*0.5f);
Vector3 vertice4 = myobject.transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, b.size.z)*0.5f);
Vector3 vertice5 = myobject.transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, -b.size.z)*0.5f);
Vector3 vertice6 = myobject.transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, -b.size.z)*0.5f);
Vector3 vertice7 = myobject.transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, b.size.z)*0.5f);
Vector3 vertice8 = myobject.transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, b.size.z)*0.5f);
TransformPoint
function applies the orientation, translation, and scale of the object's transform (and its parent transforms) to the input point.
\$\endgroup\$
If you can access a Mesh of the same size and shape, you can use Mesh.bounds, which returns positions in local space.
public static List<Vector3> GetBoxColliderCornersWorld(BoxCollider boxCollider)
{
Vector3 size = boxCollider.size;
List<Vector3> list = new();
var signs = new List<int> { -1, 1 };
signs.ForEach(signX =>
signs.ForEach(signY =>
signs.ForEach(signZ => {
var vector = new Vector3(size.x * signX, size.y * signY, size.z * signZ);
list.Add(boxCollider.transform.TransformPoint(boxCollider.center + vector * 0.5f));
})));
return list;
}