Hi,
I’m trying to achieve a rectangle image selection like this :
Basically when you look at an object a recangle is drawn around it using the bounds size.
After some research I come accross this : http://answers.unity3d.com/questions/292031/how-to-display-a-rectangle-around-a-player.html?sort=oldest
It use legacy GUI but works well, I tried to make it work with the new UI but it’s always miss place or kind of offested.
Tested with Overlay, Camera and World space canvas, I got same result.
And the code I used :
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TestImageRect : MonoBehaviour
{
public Image boundsTest;
private Vector3[] pts = new Vector3[8];
Renderer renderer;
void Awake ()
{
renderer = GetComponent<Renderer> ();
}
void Update ()
{
Bounds b = renderer.bounds;
Camera cam = Camera.main;
//The object is behind us
if (cam.WorldToScreenPoint (b.center).z < 0) return;
//All 8 vertices of the bounds
pts[0] = cam.WorldToScreenPoint (new Vector3 (b.center.x + b.extents.x, b.center.y + b.extents.y, b.center.z + b.extents.z));
pts[1] = cam.WorldToScreenPoint (new Vector3 (b.center.x + b.extents.x, b.center.y + b.extents.y, b.center.z - b.extents.z));
pts[2] = cam.WorldToScreenPoint (new Vector3 (b.center.x + b.extents.x, b.center.y - b.extents.y, b.center.z + b.extents.z));
pts[3] = cam.WorldToScreenPoint (new Vector3 (b.center.x + b.extents.x, b.center.y - b.extents.y, b.center.z - b.extents.z));
pts[4] = cam.WorldToScreenPoint (new Vector3 (b.center.x - b.extents.x, b.center.y + b.extents.y, b.center.z + b.extents.z));
pts[5] = cam.WorldToScreenPoint (new Vector3 (b.center.x - b.extents.x, b.center.y + b.extents.y, b.center.z - b.extents.z));
pts[6] = cam.WorldToScreenPoint (new Vector3 (b.center.x - b.extents.x, b.center.y - b.extents.y, b.center.z + b.extents.z));
pts[7] = cam.WorldToScreenPoint (new Vector3 (b.center.x - b.extents.x, b.center.y - b.extents.y, b.center.z - b.extents.z));
//Get them in GUI space
for (int i=0;i<pts.Length;i++) pts[i].y = Screen.height-pts[i].y;
//Calculate the min and max positions
Vector3 min = pts[0];
Vector3 max = pts[0];
for (int i=1;i<pts.Length;i++) {
min = Vector3.Min (min, pts[i]);
max = Vector3.Max (max, pts[i]);
}
Rect r = Rect.MinMaxRect (min.x,min.y,max.x,max.y);
boundsTest.rectTransform.offsetMax = max;
boundsTest.rectTransform.offsetMin = min;
}
}
If someone could help me on this that would be amazing.
Thanks!