Skip to content

Instantly share code, notes, and snippets.

@ZackAkil
Last active August 10, 2020 20:18
Show Gist options
  • Save ZackAkil/ce6604fd5ac008756f938047ce73d9d5 to your computer and use it in GitHub Desktop.
Save ZackAkil/ce6604fd5ac008756f938047ce73d9d5 to your computer and use it in GitHub Desktop.
How to produce the perfect (tight) bounding box for a game object in Unity relative to a specific camera.
private Rect Get_object_bounding_box(GameObject game_object, Camera cam)
{
// This is a relativly intense way as it is looking at each mesh point to calculate the bounding box.
// but it produces perfect bounding boxes so yolo.
// get the mesh points
Vector3[] vertices = game_object.GetComponent<MeshFilter>().mesh.vertices;
// apply the world transforms (position, rotation, scale) to the mesh points and then get their 2D position
// relative to the camera
Vector2[] vertices_2d = new Vector2[vertices.Length];
for (var i = 0; i < vertices.Length; i++)
{
vertices_2d[i] = cam.WorldToScreenPoint(game_object.transform.TransformPoint( vertices[i]));
}
// find the min max bounds of the 2D points
Vector2 min = vertices_2d[0];
Vector2 max = vertices_2d[0];
foreach (Vector2 vertex in vertices_2d)
{
min = Vector2.Min(min, vertex);
max = Vector2.Max(max, vertex);
}
// thats our perfect bounding box
return new Rect(min.x, min.y, max.x - min.x, max.y - min.y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment