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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Math between RectTransform Position and Pivot

Discussion in 'Scripting' started by AndyLangberg, Dec 11, 2018.

  1. AndyLangberg

    AndyLangberg

    Joined:
    Jul 6, 2018
    Posts:
    37
    I'm currently using a RectScroll with a script for a moveable area which can be zoomed into. This script zooms into the correct place by changing the pivot point.

    The issue comes when I now need to access the original Position X and Y of the Rect Transform (Which changes drastically when you set a new pivot point).

    Does anyone know the math between the pivot and the Position, so I can extract a position value as if the pivot was originally at 0.5?

    I.E: Position.y, at 400 on pivot 0.5 shows up as 73.45 when the pivot is at -46.28. Is there a way to use the latter two numbers to calculate back to the 400 value?
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    If we're only talking about the local values and no scaling (since you talk about zooming), the general formula is
    baseOffset + (pivot * height) = finalPos

    baseOffset is the position that your object has when pivot is 0. The pivot always adds to the position based on the height, because it indicates which percentage of the height you want to add to the object's position.

    If you know either the height or the baseOffset, which you surely do, it'll be simple math and there will be one result. The height is usually shown in the inspector as well, at least when the anchors are centered.

    You told us neither of both, but doing a quick calculation with the assumption that neither the base offset, the anchors, the height changes, the baseOffset should be ~ 396.5 and with a height close to 7.
     
    AndyLangberg likes this.
  3. AndyLangberg

    AndyLangberg

    Joined:
    Jul 6, 2018
    Posts:
    37
    Excellent, this works!

    I did not mention scaling, however I found you get to the right position by simply dividing/multiplying with it.

    Thanks for the help, this was exactly what I needed