I’ve been trying to get the bounds around a mesh so that I may draw a rectangle around it in the UI, however I’m having the worst time finding a way to do so.
I was using bounds.min and bounds.max and translating those points using WorldToScreenPoint(), but unfortunately, it merely gives me the min point and max point of the mesh in one plane. When you rotate, it looks like this:
I’d like to get it to look like this:
Could anyone point me in the right direction on this one?
I figured it out. Renderer.bounds was half the story.
The other half was not using min and max. Instead, I had to generate my own 2 coordinates based on extents. Here’s the code that explains it all:
_Center = transform.InverseTransformPoint(SelectedInfo.renderer.bounds.center);
if (_Center.z > 1)
{
_UpperLeft = camera.WorldToScreenPoint(transform.TransformPoint(_Center + new Vector3(-SelectedInfo.renderer.bounds.extents.x * 1.4F, SelectedInfo.renderer.bounds.extents.y * 1.4F, 0)));
_LowerRight = camera.WorldToScreenPoint(transform.TransformPoint(_Center + new Vector3(SelectedInfo.renderer.bounds.extents.x * 1.4F, -SelectedInfo.renderer.bounds.extents.y * 1.4F, 0)));
GUI.color = new Color(1.0f , 0, 0);//Set color to red
GUI.DrawTexture(new Rect(_UpperLeft.x, Screen.height-_UpperLeft.y, _LowerRight.x-_UpperLeft.x, _UpperLeft.y-_LowerRight.y), _ReticleTexture);
}
I took the center of the bounds and then created my own upper left and lower right coordinates using bounds.extents lengths, relative to the camera. This removes the world-based x-y plane issue. They’ll always be x-y plane relative to the camera.
After that, I retranslate them into world coordinates and then get the x,y screen coordinates and draw away! You may notice that I added a little buffer to the extents. This is to make sure there’s a little space within the rectangle. Works like a charm!