Alexander Kucherenko
Alexander Kucherenko

Reputation: 451

Unity Recttransform contains point

Is there a way to check if Rect transform contains point? Thanks in advance. I tried Bounds.Contains() and RectTransformUtility.RectangleContainsScreenPoint() but that didn't help me

private bool AreCoordsWithinUiObject(Vector2 coords, GameObject gameObj)
{
    Bounds bounds = gameObj.GetComponent<Renderer>().bounds;
    return bounds.Contains(new Vector3(coords.x, coords.y, 0));
}

This way I have an error "There is no renderer attached to the object" but I've been attached CanvasRenderer to it.

RectTransformUtility.RectangleContainsScreenPoint(gameObj.GetComponent<RectTransform>(), coords);

This method always return false

if (AreCoordsWithinUiObject(point, lines[i]))
{
    print("contains");
}

lines is a list of GameObjects

enter image description here

Upvotes: 1

Views: 13989

Answers (3)

Thomas LAURENT
Thomas LAURENT

Reputation: 1681

For a UI object container you can just use the Contains method of its rect with a local position:

container.rect.Contains(localPosition);

If you prefer working with a world position instead simply convert it to local space:

container.rect.Contains(container.InverseTransformPoint(worldPosition));

Upvotes: 1

bpgeck
bpgeck

Reputation: 1624

CanvasRenders don't have a bounds member variable. However, your task can be accomplished with just the RectTransform.rect member variable, as we can get both the width and the height of the rectangle in this fashion. My script below assumes your canvas element is anchored to the center of your Canvas. It prints "TRUE" when your mouse is inside of the element the script is attached to.

void Update()
{
    // convert pixel coords to canvas coords
    Vector2 point = Input.mousePosition - new Vector2(Screen.width / 2, Screen.height / 2); 
    Debug.Log(IsPointInRT(point, this.GetComponent<RectTransform>()));
}

bool IsPointInRT(Vector2 point, RectTransform rt)
{
    // Get the rectangular bounding box of your UI element
    Rect rect = rt.rect;

    // Get the left, right, top, and bottom boundaries of the rect
    float leftSide = rt.anchoredPosition.x - rect.width / 2;
    float rightSide = rt.anchoredPosition.x + rect.width / 2;
    float topSide = rt.anchoredPosition.y + rect.height / 2;
    float bottomSide = rt.anchoredPosition.y - rect.height / 2;

    //Debug.Log(leftSide + ", " + rightSide + ", " + topSide + ", " + bottomSide);

    // Check to see if the point is in the calculated bounds
    if (point.x >= leftSide &&
        point.x <= rightSide &&
        point.y >= bottomSide &&
        point.y <= topSide)
    {
        return true;
    }
    return false;
}

Upvotes: 9

Vladimir
Vladimir

Reputation: 41

You need to provide your UI Camera as third parameter to RectTransformUtility.RectangleContainsScreenPoint to make it work correct

Upvotes: 3

Related Questions