Monday, June 11, 2018

unity - How can I get a Box Collider's "corners" (vertices) positions?


I attached a Box Collider to a object, which has not the center as its pivot. Now I need the 8 corner points.


Right now I can only get the points in a unrotated state. But whenever I rotate the Object (which rotates in the center of the boxCollider) - everything gets messed up, because the rotation alters the gameObject-Position.


EDIT2: Solution



public Vector3[] GetColliderVertexPositions (GameObject obj)  
{
BoxCollider b = obj.GetComponent(); //retrieves the Box Collider of the GameObject called obj
Vector3[] vertices = new Vector3[8];
vertices[0] = obj.transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, -b.size.z) * 0.5f);
vertices[1] = obj.transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, -b.size.z) * 0.5f);
vertices[2] = obj.transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, b.size.z) * 0.5f);
vertices[3] = obj.transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, b.size.z) * 0.5f);
vertices[4] = obj.transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, -b.size.z) * 0.5f);
vertices[5] = obj.transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, -b.size.z) * 0.5f);

vertices[6] = obj.transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, b.size.z) * 0.5f);
vertices[7] = obj.transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, b.size.z) * 0.5f);

return vertices;
}

Found that:


Most efficient way to get the world position of the 8 vertexes of a Box Collider (C#)



Answer



Collider.bounds is an AABB (Axis-Aligned Bounding Box). An AABB is always parallel to the world axes. This figure that I just drew may help with the concept: enter image description here



Therefore, it does not have the corners of your box collider in local coordinates. Rotating it creates a weird situation.


If you are happy with AABB's, then use its coordinates without rotating. If you really need the corners of your box collider, you're going to have to use BoxCollider.offset and BoxCollider.size to calculate the local coordinates of the corners and then do Transform.TransformPoint() to get their world coordinates.


Please note: When trying to find coordinates within a BoxCollider2D, one must now use BoxCollider2D.offset instead of BoxCollider2D.center, as the latter is deprecated. The answer is updated to reflect this change.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...