모바일 가상 패드 구현
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class VirtualStick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
[SerializeField] private Image _stick;
[SerializeField] private Image _stickBG;
private Vector3 _inputVector;
public float VerticalZValue
{
get { return _inputVector.z; }
}
public float HorizontalZValue
{
get { return _inputVector.x; }
}
public void OnPointerUp(PointerEventData eventData)
{
_inputVector = Vector3.zero;
_stick.rectTransform.anchoredPosition = Vector3.zero;
}
public void OnPointerDown(PointerEventData eventData)
{
OnDrag(eventData);
}
public void OnDrag(PointerEventData eventData)
{
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(_stickBG.rectTransform, eventData.position, eventData.pressEventCamera, out pos))
{
pos.x = (pos.x / _stickBG.rectTransform.sizeDelta.x);
pos.y = (pos.y / _stickBG.rectTransform.sizeDelta.y);
Vector3 vec = new Vector3(pos.x, pos.y, 0);
vec = (vec.magnitude > 1) ? vec.normalized : vec;
_stick.rectTransform.anchoredPosition = new Vector3(vec.x * (_stickBG.rectTransform.sizeDelta.x / 2),
vec.y * (_stickBG.rectTransform.sizeDelta.y / 2));
float x = 0, y = 0;
x = (vec.x > 0.2f) ? 1 : vec.x < -0.2f ? -1 : 0;
y = (vec.y > 0.2f) ? 1 : vec.y < -0.2f ? -1 : 0;
_inputVector = new Vector3(x, 0, y);
}
}
}