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

How to compute how many pixels I should move UI?

Discussion in 'Scripting' started by Fully12, Nov 26, 2020.

  1. Fully12

    Fully12

    Joined:
    Nov 6, 2020
    Posts:
    6
    Hi,

    I have an UI that is on the bottom left corner of the screen. I need to move it to the left to move out of the screen. I made the UI depending on the 16:9 aspect ratio (1920x1080). I do some calculation to calculate how many pixels that the UI is covering on the screen, and I move it out of the screen. My problem is I need it to work on every aspect ratio. Here's the code that I've written:

    Code (CSharp):
    1.         float referenceAspectRatio = 1920.0f / 1080.0f;
    2.         float currentAspectRatio = (float)Screen.width / Screen.height;
    3.  
    4.         // 'rect' is RectTransform-type variable that is the parent UI object
    5.         float pixels = Mathf.CeilToInt(1920.0f * rect.anchorMax.x * currentAspectRatio / referenceAspectRatio);
    This code works on 16:9, 21:9, 10:9, 17:9 etc. If the second ratio is 9, it work on every aspect ratio. The problem is it doesn't work when the second ratio is not 9. For example: 16:10, 4:3, 17:10 etc. How can I calculate how many pixels that UI is covering on the screen, so I can move it?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,754
    Screen.width and Screen.height give you the size in pixels.

    But a better more flexible way is to anchor a GameObject at the edges of the UI (the entire canvas), then underneath that GameObject put other GameObjects that are your notion of "offscreen"

    At runtime you would have a reference to those "offscreen" objects and simply use their position to move the visible object from and to where it needs to go.
     
  3. Fully12

    Fully12

    Joined:
    Nov 6, 2020
    Posts:
    6
    That's actually clever, but I have more than one UI, to hide in the game and I'm looking for an algorithm for future development. (It should work for new UIs).

    I've already adjusted the anchors of the UI. All 4 of them are on the edges of the UI. I need to make an equation to calculate how much I should move the UI. The current algorithm works on every x:9 aspect ratios since the algorithm is based on 16:9.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,754
    It's all proportional rectangles via
    RectTransform
    . You need the ratio between whatever position your object is vs the .rect of the parenting canvas. There are also some helpful tools in the
    RectTransformUtility
    class to get you there.