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. https://youtu.be/NxWh290JjZs
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;
     }
 
              Answer by Didanix · Sep 22, 2017 at 08:24 AM
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;
 
              Your answer
 
             Follow this Question
Related Questions
Joystick for my game? 0 Answers
How can i make my player look at the same direction where its moving? [JOYSTICK ANDROID] 0 Answers
Using the free touchscreen Joystick my code cant detect the joystick 0 Answers
Joystick input recognized multiple times 0 Answers
Rotate a character with joystick 0 Answers