Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Get mouse position relative to UI element

Discussion in '2D' started by orilevenglick, Jun 19, 2019.

Thread Status:
Not open for further replies.
  1. orilevenglick

    orilevenglick

    Joined:
    Apr 7, 2019
    Posts:
    7
    Hello everybody,
    So I have a UI element, specifically an image. When it's clicked, I want to know exactly where the mouse is, relative to the element's bottom-left. The anchors of the element are in its center. The element is not necessarily in the middle of the screen.
    For example, when you click the bottom-left corner of the element, it should show (0,0). when you click the middle, it should show (element_width/2, element_height/2), etc.
    I tried this naive method, but it didn't work:
    Code (CSharp):
    1. public override void OnPointerClick(PointerEventData eventData)
    2. {
    3.     base.OnPointerClick(eventData);
    4.  
    5.     Vector2 relativeToCenter = eventData.position - (Vector2)transform.position;
    6.     Vector2 relativeToBottomLeft = relativeToCenter + (GetComponent<RectTransform>().sizeDelta / 2);
    7.     Debug.Log(relativeToBottomLeft);
    8. }
    What am I missing?
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
  3. orilevenglick

    orilevenglick

    Joined:
    Apr 7, 2019
    Posts:
    7
    Thank you very much!
    Here is the final code, for the people who might enter this thread looking for solutions:
    Code (CSharp):
    1. private Vector2 PointerDataToRelativePos(PointerEventData eventData)
    2. {
    3.     Vector2 result;
    4.     Vector2 clickPosition = eventData.position;
    5.     RectTransform thisRect = GetComponent<RectTransform>();
    6.  
    7.     RectTransformUtility.ScreenPointToLocalPointInRectangle(thisRect, clickPosition, null, out result);
    8.     result += thisRect.sizeDelta / 2;
    9.  
    10.     return result;
    11. }
    12.  
    I made two assumptions:
    1. the mouse is inside the image. otherwise,
    ScreenPointToLocalPointInRectangle()
    will return
    false
    , so you might want to check it in your code.
    2. the ui element is in render mode "screen space - overlay". not sure how much it affects anything, but it's good to know.
     
  4. mz00956

    mz00956

    Joined:
    Jun 29, 2019
    Posts:
    21
    I am no expert but wouldn't it be smarter to put the "GetComponent" into start so the function doesn't always call it. The RectTransform shouldn't change normaly
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,525
    Please don't necro old posts. I'll close this thread too because it's asking about UI on the 2D forum.
     
Thread Status:
Not open for further replies.