2y ago · Jan 20, 2024 3:10 PM
Unlike axis-aligned 2D boxes, a full 3D bounding box rotates accurately with the entity's orientation ().
How to calculate the 8 rotated corners in Unity C#:
CODE
Transform.rotationHow to calculate the 8 rotated corners in Unity C#:
CSHARP
using UnityEngine;
public static class Box3DESP
{
public static void Draw3DBox(Bounds localBounds, Transform entityTransform, Camera camera, Color color)
{
Vector3 min = localBounds.min;
Vector3 max = localBounds.max;
// 8 Corner points in local object space
Vector3[] corners = new Vector3[8]
{
new Vector3(min.x, min.y, min.z),
new Vector3(max.x, min.y, min.z),
new Vector3(max.x, min.y, max.z),
new Vector3(min.x, min.y, max.z),
new Vector3(min.x, max.y, min.z),
new Vector3(max.x, max.y, min.z),
new Vector3(max.x, max.y, max.z),
new Vector3(min.x, max.y, max.z)
};
Vector2[] screenCorners = new Vector2[8];
for (int i = 0; i < 8; i++)
{
// Transform point from local to world space with rotation
Vector3 worldPoint = entityTransform.TransformPoint(corners[i]);
Vector3 screenPoint = camera.WorldToScreenPoint(worldPoint);
if (screenPoint.z <= 0.01f) return; // Behind camera
screenCorners[i] = new Vector2(screenPoint.x, Screen.height - screenPoint.y);
}
// Draw 12 connecting edges using Unity GUI line drawing
DrawLine(screenCorners[0], screenCorners[1], color);
DrawLine(screenCorners[1], screenCorners[2], color);
DrawLine(screenCorners[2], screenCorners[3], color);
DrawLine(screenCorners[3], screenCorners[0], color);
DrawLine(screenCorners[4], screenCorners[5], color);
DrawLine(screenCorners[5], screenCorners[6], color);
DrawLine(screenCorners[6], screenCorners[7], color);
DrawLine(screenCorners[7], screenCorners[4], color);
for (int i = 0; i < 4; i++)
{
DrawLine(screenCorners[i], screenCorners[i + 4], color);
}
}
private static void DrawLine(Vector2 start, Vector2 end, Color color)
{
float angle = Mathf.Atan2(end.y - start.y, end.x - start.x) * Mathf.Rad2Deg;
float length = Vector2.Distance(start, end);
GUIUtility.RotateAroundPivot(angle, start);
GUI.color = color;
GUI.DrawTexture(new Rect(start.x, start.y, length, 1.5f), Texture2D.whiteTexture);
GUIUtility.RotateAroundPivot(-angle, start);
}
}
MatrixRecon · 3D Mathematics & View Matrix Calculations
The following users thanked MatrixRecon for this post: