10/31

이우석·2023년 10월 31일
0

SBS 국기수업

목록 보기
66/120

모바일 가상 패드 구현

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);
        }
	}
}
profile
게임 개발자 지망생, 유니티 공부중!

0개의 댓글