Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Center point of a RectTransform

Discussion in 'UGUI & TextMesh Pro' started by FlightOfOne, Jun 2, 2022.

  1. FlightOfOne

    FlightOfOne

    Joined:
    Aug 1, 2014
    Posts:
    668
    I have been trying to figure this out for hours now and every answer I find seem to get thrown off with some setting but mainly depending on where the pivot is set to.

    How do I find the center position of a RecTransform, in Screen Space (or relative to the canvas, either is useful), regardless of what scale, pivot anchor or canvas settings?

    p.s. I am trying to figure out of one ui element is within another and this (first answer) seem to work but only as long as pivot is in the center: https://stackoverflow.com/questions/42043017/check-if-ui-elements-recttransform-are-overlapping

    Thanks!
     
  2. FlightOfOne

    FlightOfOne

    Joined:
    Aug 1, 2014
    Posts:
    668
    NVM! Finally figured it out...

    var centerPoint= rectTransform.TransformPoint(rectTransform.rect.center);


    now everything works as intended.
     
  3. unity_QJ7RazXzghZCzA

    unity_QJ7RazXzghZCzA

    Joined:
    Jul 9, 2021
    Posts:
    104
    Sorry but you are wrong and just lucky that your implementation works as intended in your case. For Screen Space Overlay you just need to read transform.position to get its screen position.
     
  4. i4EG-Kingstone

    i4EG-Kingstone

    Joined:
    Jul 18, 2018
    Posts:
    1
    Since this is the highest viewed source on Google, I'll quickly denote this answer as semi-correct, for others stumbling upon it.

    The rough summarization:

    (ObjectTransform).TransformPoint


    Does nothing else than convert the local space position to the objects world position.

    There is no luck involved that the implementation works, as the RectTransform position - irrelevant if the canvas is set to Screenspace - Overlay/Camera or World space - will always return positions which can be transformed into the correlating Screen Space given the correct matrices.

    Or in short;

    RectTransformUtility.WorldToScreenPoint(Camera, Worldpos)


    Alas the implementation in this thread is just one of many ways to use the center bounds of an object, if the pivot is not in center.

    The only "issues" that can occur, are skewed result positions, depending on the scaling of the object, but it's such a bening issue that hardly anyone will even be able to eyeball it to too much.

    Lastly, you can indeed get the position of an object via transform.position;
    note that this will always be the position of the objects pivot, not it's center.

    With that said, I wish happy tidings on everyone's development journey.
     
    emredesu and JegoBestaatal like this.