Unity/Unity자체

마우스 조이스틱

아리에 2020. 3. 9. 17:15

개선이 조금 필요함

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Move : MonoBehaviour
{

    private float moveSpeed;
    private Transform tr;
    private Vector2 initTouchDown;
    private Vector2 initDrag;

    private void Start()
    {
        tr = GetComponent();
        moveSpeed = 0.1f;
    }


    private void Update()
    {
        PlayerMove();
    }

    private void PlayerMove()
    {
        if (Input.GetMouseButtonDown(0))
        {
            initTouchDown = Input.mousePosition;
        }

        if (Input.GetMouseButton(0))
        {
            initDrag = Input.mousePosition;
            initDrag = (initDrag - initTouchDown).normalized;
            Debug.Log("initTouchDown : " + initTouchDown + "  initDrag : " + initDrag);
            tr.Translate(initDrag * moveSpeed);
        }
    }
}

 

========================================================================================================================================================

약간 개선된 코드

    using UnityEngine;

    public class Move : MonoBehaviour
    {

        private float moveSpeed;
        private Transform tr;
        private Vector2 initTouchDown;
        private Vector2 initDrag;

        private void Start()
        {
            tr = GetComponent();
            moveSpeed = 0.1f;
        }



        private void Update()
        {
            PlayerMove();
        }

        private void PlayerMove()
        {
            if (Input.GetMouseButtonDown(0))
            {
                initTouchDown = Input.mousePosition;
            }

            if (Input.GetMouseButton(0))
            {
                initDrag = Direction(initTouchDown, Input.mousePosition);
                tr.Translate(initDrag * moveSpeed);
            }
        }

        private Vector2 Direction(Vector2 fir, Vector2 sec)
        {
            if (fir.x <= sec.x + 50 && fir.x >= sec.x - 50)
            {
                if (fir.y <= sec.y + 50 && fir.y >= sec.y - 50)
                    return Vector2.zero;
                else
                    return new Vector2(0, sec.y - fir.y).normalized;
            }
            else
            {
                if (fir.y <= sec.y + 50 && fir.y >= sec.y - 50)
                    return new Vector2(sec.x - fir.x, 0).normalized;
                else
                    return (sec - fir).normalized;
            }
        }
    }