So I’ve been wanting to add full controller support to a current project (which is coming along fairly quickly).
However I’ve created a custom mouse using GUI texture and use the controller axis to move it (since Unity doesn’t support editing windows cursor position etc.)
My issue now is detecting when the texture is over another uGUI? I’d rather not remake the menu system if I don’t have to. There 3 buttons that each have a text child. these 3 buttons are all under the same parent canvas.
How would I go about detecting if the custom 2Dtexture is within any of the buttons locations?
I’ve seen something about Rect.Contains(); But is this going to help?
Do I need to convert the button objects from world to screen point then check if my rect contains both the texture and the button?
Or similarly convert button to screen point and check the X/Y to the textures X/Y?
So with using this extension below and taking my custom cursor position and passing that in the Rect.Contains() I now have a correct position for each button that I can interact with.
using UnityEngine;
using System.Collections;
public static class RectTransformExtension {
public static Rect GetScreenRect(this RectTransform rectTransform, Canvas canvas) {
Vector3[] corners = new Vector3[4];
Vector3[] screenCorners = new Vector3[2];
rectTransform.GetWorldCorners(corners);
if (canvas.renderMode == RenderMode.ScreenSpaceCamera || canvas.renderMode == RenderMode.WorldSpace)
{
screenCorners[0] = RectTransformUtility.WorldToScreenPoint(canvas.worldCamera, corners[1]);
screenCorners[1] = RectTransformUtility.WorldToScreenPoint(canvas.worldCamera, corners[3]);
}
else
{
screenCorners[0] = RectTransformUtility.WorldToScreenPoint(null, corners[1]);
screenCorners[1] = RectTransformUtility.WorldToScreenPoint(null, corners[3]);
}
screenCorners[0].y = Screen.height - screenCorners[0].y;
screenCorners[1].y = Screen.height - screenCorners[1].y;
return new Rect(screenCorners[0], screenCorners[1] - screenCorners[0]);
}
}
And in my code:
Vector2 mouseVector = new Vector2(currentX, currentY);
RectTransform newRectT = buttonGameObject.GetComponent<RectTransform>();
Rect newRect = RectTransformExtension.GetScreenRect(newRectT, myParentCanvas);
if (newRect.Contains(mouseVector))
{
Debug.Log("Mouse Over:");
}