Search Unity

Unity UI Is transform.position of an UI element its pixel coordinates?

Discussion in 'UGUI & TextMesh Pro' started by Zamor999, Apr 21, 2019.

  1. Zamor999

    Zamor999

    Joined:
    Oct 15, 2015
    Posts:
    10
    Hi!

    I'm doing some 2D vector math with UI elements and needed a vector from my UI element to the mouse position so I wrote this:

    Code (CSharp):
    1. Vector2 pointingToMouse = Input.mousePosition - transform.position;
    I didn't really think over it because it worked fine but isn't Input.mousePosition in pixel coordinates and transform.position in world coordinates?
     
    Last edited: Apr 21, 2019
  2. dadude123

    dadude123

    Joined:
    Feb 26, 2014
    Posts:
    789
    Yes mousePosition is in pixel coords (with the Y axis flipped actually, unity's 0,0 is at the lower left)

    But if your transform is an UGUI element then that uses pixel coords too.
    By the way: That's why the main UGUI canvas is so gigantic (compared to gameobjects), because it works in pixel coordinates. So no surprise there. That's why it works.

    Keep in mind that transform.position is where the PIVOT of your element is.
    Sure, its' 0.5, 0.5 by default, so it works for now, but you might quickly encounter situations where other systems have changed the pivot of some elements, or maybe (or rather, most likely) you'll eventually get into a situation where you want the pivot of some element to be different as well.

    Like custom layout containers might want to (or need to) control the pivot and/or anchor settings of their child elements as well. The default unity ones don't afaik, but there are lots of reasons why more advanced containers might mess with those properties.

    Using transform.position might work for simple scenarios, but you should take a look at the RectTransforms .rect and other properties to reliably determine the actual center...


    Also keep the RectTransformUtilities class in mind. It has some methods that are useful sometimes.
     
  3. Zamor999

    Zamor999

    Joined:
    Oct 15, 2015
    Posts:
    10
    Great answer! Thanks