UPF/Assets/Game/Scripts/joystick.cs
2022-06-05 00:16:16 +05:30

80 lines
2.1 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class joystick : MonoBehaviour
{
public bool DissappearOnEnd = true;
private Vector3 defaultPosition;
public bool touchDown;
public bool autoConfigMaxDist;
public float maxDist = 100;
public Vector2 input;
private Vector2 deltaPos;
private Vector2 startPos;
private Vector2 endPos;
public RectTransform joyBG;
public RectTransform joyStick;
void Start(){
defaultPosition = joyBG.position;
}
public void onDrag(BaseEventData pointer)
{
PointerEventData ped = pointer as PointerEventData;
endPos = ped.position;
deltaPos = endPos - startPos;
deltaPos = new Vector2(Mathf.Clamp(deltaPos.x, -maxDist, maxDist), Mathf.Clamp(deltaPos.y, -maxDist, +maxDist));
Vector2 _input = new Vector2(deltaPos.x / maxDist, deltaPos.y / maxDist);
if (_input.magnitude < 0.1f)
{
return;
}
input = _input;
input = (input.magnitude > 1.0f) ? input.normalized : input;
joyStick.localPosition = new Vector2(input.x * (joyBG.sizeDelta.x / 2f), input.y * (joyBG.sizeDelta.y / 2f));
}
public void pointerDown(BaseEventData pointer)
{
PointerEventData ped = pointer as PointerEventData;
startJoy(ped);
}
public void pointerUp()
{
endJoy();
}
void startJoy(PointerEventData pointer)
{
startPos = pointer.position;
joyBG.gameObject.SetActive(true);
joyStick.gameObject.SetActive(true);
joyStick.localPosition = Vector2.zero;
joyBG.position = startPos;
touchDown = true;
}
void endJoy()
{
input=Vector2.zero;
joyBG.position = defaultPosition;
joyStick.localPosition = Vector2.zero;
joyBG.gameObject.SetActive(!DissappearOnEnd);
joyStick.gameObject.SetActive(!DissappearOnEnd);
touchDown = false;
}
}