'joystick positioning relative to screen size

I want the joystick fixed on the bottom-right the screen, no matter the resolution/window size. Although my solution works, there must be a cleaner code for this or some canvas option I don't know about.

I tried and tested a position that works on a set resolution and then factor the new resolution to that. Tested on resolutions: 434x494 and 1920x1080

For 434 pixel wide screen a joystick position.x of 434 - 115 = 319. The factor was too big so I had to square root it for width.

For the height 120 worked for 494 height screen, I just did some hocus pocus to make it work for 1920x1080.

    public Joystick joystick;
    public Vector3 m_myPosition;
    public RectTransform m_NewTransform;

    void Start()
    {
        double width = Screen.width - (Mathf.Sqrt(Screen.width / 434)) * 115;
        double height = 120 + (4* Mathf.Exp(Screen.width / 494));
        m_myPosition.x = (float)width;
        m_myPosition.y = (float)height;
        m_NewTransform.position = m_myPosition;
    }

I shouldn't rely on iffy code like this, any solutions?



Solution 1:[1]

G'day folks

Solution is everywhere on youtube... You just change the canvas UI scale to 'Scale to screen size' and then Anchor the UI joystick object to a direction. For my joystick I just anchored it to bottom-right and done!

In case you want in depth info on how to; I followed this tutorial: https://www.youtube.com/watch?v=w3sMD-3OJro

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 criticalories