Unity2D
Unity) [유니티 2D] 가상 조이스틱을 통한 Rotation 변경
HSH12345
2023. 2. 26. 15:17
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class JoystickGunShot : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
public RectTransform frame;
public RectTransform handle;
private float handleRange = 130;
private Vector3 input;
public float Horizontal { get { return input.x; } }
public float Vertical { get { return input.y; } }
public Vector3 Input { get { return input; } }
public void OnDrag(PointerEventData eventData)
{
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
this.gameObject.GetComponent<RectTransform>(), eventData.position,
eventData.pressEventCamera, out Vector2 localVector))
{
if (localVector.magnitude < this.handleRange)
{
this.handle.transform.localPosition = localVector;
}
else
{
this.handle.transform.localPosition = localVector.normalized * this.handleRange;
}
this.input = localVector;
}
this.SetJoystickColor(true);
}
public void OnPointerUp(PointerEventData eventData)
{
this.input = Vector2.zero;
this.handle.anchoredPosition = Vector2.zero;
this.SetJoystickColor(false);
}
public void OnPointerDown(PointerEventData eventData)
{
this.OnDrag(eventData);
}
private void SetJoystickColor(bool isOnDraged)
{
Color pointedFrameColor;
Color pointedHandleColor;
if (isOnDraged)
{
pointedFrameColor = new Color(255, 0, 0, 0.5f);
pointedHandleColor = new Color(255, 0, 0, 0.6f);
}
else
{
pointedFrameColor = new Color(255, 255, 255, 0.5f);
pointedHandleColor = new Color(255, 255, 255, 0.6f);
}
this.frame.gameObject.GetComponent<Image>().color = pointedFrameColor;
this.handle.gameObject.GetComponent<Image>().color = pointedHandleColor;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunRotation : MonoBehaviour
{
private JoystickGunShot joystickGunShot;
private float angle;
public float Angle { get { return angle; } }
public void Init()
{
this.joystickGunShot = GameObject.FindObjectOfType<JoystickGunShot>();
StartCoroutine(CheckGunRotationRoutine());
}
IEnumerator CheckGunRotationRoutine()
{
while (true)
{
RotateGun();
yield return null;
}
}
void RotateGun()
{
if (this.joystickGunShot.Input == Vector3.zero) return;
this.angle = Mathf.Atan2(this.joystickGunShot.Vertical, this.joystickGunShot.Horizontal) * Mathf.Rad2Deg + 90;
var lookRotation = Quaternion.Euler(angle * Vector3.forward);
this.transform.rotation = lookRotation;
}
}
- Mathf.Atan2(x, y) 메서드를 통하여 x와 y 사이의 각도 r을 구할 수 있다. Atan(x,y) 메서드는 0을 매개변수로 받았을 때 발생하는 오류를 처리할 수 있는 기능이 없으므로 Atan2를 주로 사용한다. 또한 각도(r)은 라디안 값이기 때문에 Mathf.Red2Deg을 곱하여 라디안을 상수로서 각도로 사용한다.