using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class JoystickMove : Joystick
{
public RectTransform frame2;
public RectTransform bg;
private Vector2 touchPos;
public override void OnPointerUp(PointerEventData eventData)
{
this.input = Vector2.zero;
this.handle.anchoredPosition = touchPos;
this.frame2.anchoredPosition = touchPos;
this.SetJoystickColor(false);
this.isDragged = false;
}
public override void OnDrag(PointerEventData eventData)
{
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
this.gameObject.GetComponent<RectTransform>(), eventData.position,
eventData.pressEventCamera, out Vector2 localVector))
{
var moveJoystickDir = localVector - this.touchPos;
if (moveJoystickDir.magnitude < this.handleRange)
{
this.handle.anchoredPosition = localVector;
}
else
{
this.handle.anchoredPosition = this.touchPos + moveJoystickDir.normalized * this.handleRange;
}
this.input = moveJoystickDir;
}
this.SetJoystickColor(true);
}
public override void OnPointerDown(PointerEventData eventData)
{
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
this.gameObject.GetComponent<RectTransform>(), eventData.position,
eventData.pressEventCamera, out Vector2 localVector))
{
this.touchPos = localVector;
this.handle.anchoredPosition = localVector;
this.frame.anchoredPosition = localVector;
this.frame2.anchoredPosition = localVector;
}
this.OnDrag(eventData);
this.isDragged = true;
}
protected override void SetJoystickColor(bool isOnDraged)
{
base.SetJoystickColor(isOnDraged);
Color pointedFrameColor;
Color pointedFrame2Color;
if (isOnDraged)
{
pointedFrameColor = new Color(255, 0, 0, 0.5f);
pointedFrame2Color = new Color(255, 0, 0, 0f);
}
else
{
pointedFrameColor = new Color(255, 255, 255, 0f);
pointedFrame2Color = new Color(255, 255, 255, 0.5f);
}
this.frame.gameObject.GetComponent<Image>().color = pointedFrameColor;
this.frame2.gameObject.GetComponent<Image>().color = pointedFrame2Color;
}
}
좌측에 RectTransform 백그라운드를 만들어 터치되는 부분을 기준으로 이동 벡터 값을 구하여 플레이어가 이동시키도록 구현하였습니다.
'Unity2D' 카테고리의 다른 글
Unity) [유니티 2D] 셰이더를 활용하여 이미지 흰색으로 변경 (0) | 2023.05.15 |
---|---|
Unity) [UGUI] 터치하면 팝업, 터치를 떼면 팝업이 꺼지는 기능 구현 (0) | 2023.05.14 |
Unity) [유니티 2D] 타일맵 Collider 사이즈 관련 (0) | 2023.05.08 |
Unity) [유니티 2D] 베지어 곡선을 통한 데미지 텍스트 구현 (0) | 2023.05.06 |
Unity) [유니티 2D] 데이터 테이블을 연동하여 다양한 몬스터 생성하기 (0) | 2023.05.06 |