On-screen joystick snaps to lower-left on first press c#

I’m using an on-screen joystick in my Unity game. When I run the game in the editor and press anywhere in the joystick area, the joystick control initially snaps to the bottom-left corner, then as the drag continues it snaps back to following the cursor as expected.

I’ve recorded a video of the issue.

Here is the joystick code - any idea why it’s snapping like this at the start of a click/drag?

    private Image bgImage;
    private Image joystickImage;
    public Vector3 InputDirection { set; get; }

    private void Start()
    {
        bgImage = GetComponent<Image>();
        joystickImage = transform.GetChild(0).GetComponent<Image>();
        InputDirection = Vector3.zero;
    }

    public virtual void OnDrag(PointerEventData Ped)
    {
        Vector2 pos = Vector2.zero;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImage.rectTransform, Ped.position, Ped.pressEventCamera, out pos))
        {
            pos.x = (pos.x / bgImage.rectTransform.sizeDelta.x);
            pos.y = (pos.y / bgImage.rectTransform.sizeDelta.y);

            float x = (bgImage.rectTransform.pivot.x == 1) ? pos.x * 2 + 1 : pos.x * 2 - 1;
            float y = (bgImage.rectTransform.pivot.y == 1) ? pos.y * 2 + 1 : pos.y * 2 - 1;

            InputDirection = new Vector3(x, 0, y);
            //InputDirection = new Vector3(pos.x * 1 + 1, 0, pos.y * 1 - 1);
            InputDirection = (InputDirection.magnitude > 1.0f) ? InputDirection.normalized : InputDirection;
             
            joystickImage.rectTransform.anchoredPosition = new Vector3(InputDirection.x * (bgImage.rectTransform.sizeDelta.x / 3), InputDirection.z * (bgImage.rectTransform.sizeDelta.y/3));
        }
    }

    public virtual void OnPointerDown(PointerEventData Ped)
    {
        OnDrag(Ped);
    }

    public virtual void OnPointerUp(PointerEventData Ped)
    {
        InputDirection = Vector3.zero;
        joystickImage.rectTransform.anchoredPosition = Vector3.zero;
    }

1 Answer

1

Change the following lines from

float x = (bgImage.rectTransform.pivot.x == 1) ? pos.x * 2 + 1 : pos.x * 2 - 1;
float y = (bgImage.rectTransform.pivot.y == 1) ? pos.y * 2 + 1 : pos.y * 2 - 1;

to

float x = (bgImage.rectTransform.pivot.x == 1) ? pos.x * 2 + 1 : pos.x * 2;
float y = (bgImage.rectTransform.pivot.y == 1) ? pos.y * 2 + 1 : pos.y * 2;

You can take a look at my other comment. I hope that explains it.