Hey all. I'm making a UI element that adjusts to the size of a collider world space as an indicator for aim assist. To do this, I'm getting all the points on the collider bounds, converting them to screen space, and making a screen space box around the points that are furthest from the center of the collider. This calculation works, however it appears to have some issues with the perspective camera when rotating and when changing screen resolution (see attatched video). How can I account for this in my calculation?
Vector3[] points = new Vector3[8];
// get all points on collider bounds
points[0] = new Vector3(testTarget.bounds.min.x, testTarget.bounds.min.y, testTarget.bounds.min.z); // bottom left close
points[1] = new Vector3(testTarget.bounds.min.x, testTarget.bounds.min.y, testTarget.bounds.max.z); // bottom left far
points[2] = new Vector3(testTarget.bounds.min.x, testTarget.bounds.max.y, testTarget.bounds.min.z); // top left close
points[3] = new Vector3(testTarget.bounds.min.x, testTarget.bounds.max.y, testTarget.bounds.max.z); // top left far
points[4] = new Vector3(testTarget.bounds.max.x, testTarget.bounds.min.y, testTarget.bounds.min.z); // bottom right close
points[5] = new Vector3(testTarget.bounds.max.x, testTarget.bounds.min.y, testTarget.bounds.max.z); // bottom right far
points[6] = new Vector3(testTarget.bounds.max.x, testTarget.bounds.max.y, testTarget.bounds.min.z); // top right close
points[7] = new Vector3(testTarget.bounds.max.x, testTarget.bounds.max.y, testTarget.bounds.max.z); // top right far
Vector3 screenSpaceBottomCorner = new Vector3(Mathf.Infinity, Mathf.Infinity);
Vector3 screenSpaceTopCorner = new Vector3(-Mathf.Infinity, -Mathf.Infinity);
Vector3 screenSpaceCenter = Camera.main.WorldToScreenPoint(testTarget.bounds.center);
for (int i = 0; i < points.Length; i++)
{
Vector3 screenSpacePoint = Camera.main.WorldToScreenPoint(points[i]);
if (screenSpacePoint.x < screenSpaceBottomCorner.x) screenSpaceBottomCorner.x = screenSpacePoint.x;
if (screenSpacePoint.y < screenSpaceBottomCorner.y) screenSpaceBottomCorner.y = screenSpacePoint.y;
if (screenSpacePoint.x > screenSpaceTopCorner.x) screenSpaceTopCorner.x = screenSpacePoint.x;
if (screenSpacePoint.y > screenSpaceTopCorner.y) screenSpaceTopCorner.y = screenSpacePoint.y;
}
_aimAssistCrosshair.sizeDelta = new Vector2(
Mathf.Abs(screenSpaceTopCorner.x - screenSpaceBottomCorner.x),
Mathf.Abs(screenSpaceTopCorner.y - screenSpaceBottomCorner.y));
_aimAssistCrosshair.position = screenSpaceCenter;```