Hi all,
I am trying to achieve an effect where a window will pop up on screen next to an object with it’s information when the mouse is hovering over a gameobject.
The gameobject has a collider with IsTrigger = true. So onMouseXXX works.
It is easy to get the position of the object on screen but I am struggling to calculate the size of the object in screen co-ordinates and especially when the camera moves.
My code so far is:
using UnityEngine;
public class SelectionScript : MonoBehaviour
{
private bool IsMouseOver;
private Rect WindowRect = new(0, 0, 100, 100);
private int WindowID;
private string WindowName;
Renderer _renderer;
private void Start()
{
WindowID = GetHashCode();
WindowName = gameObject.name;
_renderer = GetComponent<Renderer>();
}
private void OnGUI()
{
if (!IsMouseOver) return;
Rect rect = new Rect();
rect.position = WorldToGuiPoint(gameObject.transform.position);
// Ok, fine so far but how do I find the size o fthe object in screen space co-ordinates?
// I know I can use renderer.bounds. min and max but this doesn't seem to take perspective into consideration..
rect.width = 100;
rect.height = 100;
Utils.DrawScreenRectBorder(rect, 2, new Color(0.0f, 0.0f, 0.0f)); // This is a seperate script but works.
// I would like the onGUI window to pop up on the top Right of the object and not obscure it (if it does
// this can lead to a flickering effect if the cursor is over the object but also in the window as the
// onMouseOver toggles on/off eavery other frame)
WindowRect = GUILayout.Window(WindowID, WindowRect, WindowFunc, WindowName);
}
void WindowFunc(int id)
{
GUILayout.Label("Hello World");
}
private void OnMouseOver()
{
IsMouseOver = true;
}
private void OnMouseExit()
{
IsMouseOver = false;
}
public Vector2 WorldToGuiPoint(Vector3 GOposition)
{
Vector2 guiPosition = Camera.main.WorldToScreenPoint(GOposition);
guiPosition.y = Screen.height - guiPosition.y;
return guiPosition;
}
// Not used but for investigation purposes!
public void OnDrawGizmos()
{
Renderer r = GetComponent<Renderer>();
if (r == null)
return;
Gizmos.matrix = Matrix4x4.identity;
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(r.bounds.center, r.bounds.extents * 2);
}
}
Has anyone solved this problem or have any good ideas? Thank you in advance.
Michael