Here is the code below:Made an easy to use Virtual Joystick controller. I did this for easing in new devs for into mobile gaming. More details in my blog. https://t.co/OAPSU5gDTL pic.twitter.com/ZQKVU85dnR
— Rami Morrar (@RamiMorrar97) October 20, 2019
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class VirtualJoyStick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
private Image Background;
private Image Joystickimg;
private Vector3 inputvector;
private void Start()
{
Background = GetComponent<Image>();
Joystickimg = transform.GetChild(0).GetComponent<Image>();
}
public void OnDrag(PointerEventData ped)
{
Vector2 pos;
if(RectTransformUtility.ScreenPointToLocalPointInRectangle(Background.rectTransform, ped.position, ped.pressEventCamera, out pos)){
pos.x = (pos.x / Background.rectTransform.sizeDelta.x);
pos.y = (pos.y / Background.rectTransform.sizeDelta.y);
inputvector = new Vector3(pos.x * 4 + 1, 0, pos.y * 4 - 1);
inputvector = (inputvector.magnitude > 1.0f) ? inputvector.normalized : inputvector;
//Move joystick img
Joystickimg.rectTransform.anchoredPosition =
new Vector3(inputvector.x * (Background.rectTransform.sizeDelta.x / 3), inputvector.z * (Background.rectTransform.sizeDelta.y / 3));
}
}
// Start is called before the first frame update
public void OnPointerDown(PointerEventData ped)
{
OnDrag(ped);
}
public 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");
}
}
No comments:
Post a Comment