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 백그라운드를 만들어 터치되는 부분을 기준으로 이동 벡터 값을 구하여 플레이어가 이동시키도록 구현하였습니다.

 

+ Recent posts