I’m wanting to draw a GUI.Rect around a 2D sprite. The purpose is a simple UI selection box when the object is clicked. I’ve found my way to a working solution:
- Use the SpriteRenderer’s center and extents to locate the top left corner.
- Use the same to find the bottom right corner.
- Finding the difference between the two to arrive at a height and width.
- Drawing the rect with the top left vector + height and width.
Here’s the code (omitting a Camera.main conversion from world to screen space for the purposes of the Rect) —
Vector3 topLeft_worldSpace = new Vector3(spriteRenderer.bounds.center.x - spriteRenderer.bounds.extents.x, -spriteRenderer.bounds.center.y - spriteRenderer.bounds.extents.y, 0);
Vector3 bottomRight_worldSpace = new Vector3(spriteRenderer.bounds.center.x + spriteRenderer.bounds.extents.x, spriteRenderer.bounds.center.y + spriteRenderer.bounds.extents.y, 0);
Vector3 size = bottomRight_screenSpace - topLeft_screenSpace;
Rect rect = new Rect(topLeft_screenSpace.x, topLeft_screenSpace.y, size.x, size.y);
And it works! Until…
When I move my sprite in world space, the rect goes completely haywire. It moves around world space as the sprite moves about.
I suspect the issue is the sprite’s rotation is not being accounted for, but that’s only a hunch.
(In the image below, my Rect has suddenly stretched very tall. Other times, it’s very small, or very wide. In other words, I’m using completely the wrong values!)
Any advice on how best to achieve this? I promise before posting this, I’ve spent days fiddling. I’m just missing something.