Hi, i am trying to make a joystick to move my character.
This is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;
public class VirtualJoystick : MonoBehaviour , IDragHandler, IPointerDownHandler, IPointerUpHandler
{
private Image BgIMG,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.y);
InputVector = new Vector3(pos.x * 2 + 1, 0, pos.y * 2 - 1);
InputVector = (InputVector.magnitude > 1.0f) ? InputVector.normalized: InputVector;
//Move joystick image
JoystickIMG.rectTransform.anchoredPosition = new Vector3(InputVector.x * (BgIMG.rectTransform.sizeDelta.x / 3), InputVector.z * (BgIMG.rectTransform.sizeDelta.y / 3));
Debug.Log(pos);
}
}
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.z != 0)
{
return InputVector.z;
}
else return Input.GetAxis("Vertical");
}
}
And this is my code in my player
private Vector3 MoveInput()
{
Vector3 dir = Vector3.zero;
dir.x = Joystick.Horizontal();
dir.z = Joystick.Vertical();
if (dir.sqrMagnitude > 1)
dir.Normalize();
return dir;
}
The joystick is moving and get back to his place when i release the mouse, but the character is not moving.