2

I'm trying to make a simple game where a ball moves, but there's a problem. When I press the joystick the player moves correctly,but at every time I touch the joystick it first go in the bottom-left position and not where I just clicked. The position in the screen is where it goes even if I touch another place enter image description here

Here's the script of the joystick:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;

public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{

private Image bgImg;
private Image joystickImg;
private Vector3 inputVector;

private void Start()
{
    bgImg = GetComponent<Image>();
    joystickImg = transform.GetChild(0).GetComponent<Image>();
}

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

        inputVector = new Vector3(pos.x * 2 + 1, 0, pos.y * 2 - 1);
        inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;

        // Move joystickImg
        joystickImg.rectTransform.anchoredPosition =
            new Vector3(inputVector.x * bgImg.rectTransform.sizeDelta.x / 3
                , inputVector.z * (bgImg.rectTransform.sizeDelta.y / 3));

    }
}

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

public virtual void OnPointerUp(PointerEventData ped)
{
    inputVector = Vector3.zero;
    joystickImg.rectTransform.anchoredPosition = Vector3.zero;
}

public float Horizontal()
{
    if (inputVector.x != 0)
        return inputVector.x;
    else
        return Input.GetAxis("Horizontal");
}

public float Vertical()
{
    if (inputVector.x != 0)
        return inputVector.z;
    else
        return Input.GetAxis("Vertical");
}
}
  • Maybe have a look at the [Joystick Pack](https://assetstore.unity.com/packages/tools/input-management/joystick-pack-107631) for some ideas. – Iggy Feb 25 '20 at 00:52

1 Answers1

0

I notice in OnDrag() you set pos.y using bgImg.rectTransform.sizeDelta.x instead of bgImg.rectTransform.sizeDelta.y.

And in Vertical() you are also checking inputVector.x instead of inputVector.z.

These most likely won't fix the bug but they are good fixes to make.

What will work is removing the offset in

inputVector = new Vector3(pos.x * 2 + 1, 0, pos.y * 2 - 1);

Change this to

inputVector = new Vector3(pos.x * 2, 0, pos.y * 2);

removing the +1 and -1, and that should fix it!

Spencer Stream
  • 616
  • 2
  • 6
  • 22