Unityマウスを上下左右にドラッグ

13454 ワード

Unityマウスを上下左右にドラッグ
public class Logic : MonoBehaviour
{
    private float StartMouseLocationX;
    private float StartMouseLocationY;
    private float EndMouseLocationX;
    private float EndMouseLocationY;

    #region           
    private void OnMouseDown()
    {
        if (Input.GetMouseButtonDown(0))
        {
            StartMouseLocationX = Input.mousePosition.x;
            StartMouseLocationY = Input.mousePosition.y;
            //               
            EndMouseLocationX = StartMouseLocationX;
            EndMouseLocationY = StartMouseLocationY;
        }
    }
    #endregion
    
    #region           
    private void OnMouseUp()
    {
        if (Input.GetMouseButtonUp(0))
        {
            EndMouseLocationX = Input.mousePosition.x;
            EndMouseLocationY = Input.mousePosition.y;
        }

    }
    #endregion

    #region            
     private bool IfDrag()
    {
        if (MouseMoveDistitens(StartMouseLocationX, StartMouseLocationY, EndMouseLocationX, EndMouseLocationY) < 10)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    #endregion

    #region         
    private float MouseMoveDistitens(float Startx,float Starty,float Endx,float Endy)
    {
        return Mathf.Sqrt((Startx - Endx) * (Startx - Endx) + (Starty - Endy) * (Starty - Endy));
    }
    #endregion

    #region         
    private string MoveDirection()
    {
        if (Mathf.Abs(EndMouseLocationX - StartMouseLocationX) > Mathf.Abs(EndMouseLocationY - StartMouseLocationY))//             
        {
            if (EndMouseLocationX - StartMouseLocationX > 0)//         
            {
                DataZeroing();//               
                return "Right";
            }
            else
            {
                DataZeroing();
                return "Left";
            }
        }
        else
        {
            if (EndMouseLocationY - StartMouseLocationY > 0)//         
            {
                DataZeroing();
                return "Up";
            }
            else
            {
                DataZeroing();
                return "Down";
            }
        }
    }
        #endregion

    #region     
       private void DataZeroing()
        {
            StartMouseLocationX = 0;
            StartMouseLocationY = 0;
            EndMouseLocationX = 0;
            EndMouseLocationY = 0;
        }
        #endregion

    void Update()
    {
        if (IfDrag())
        {
            Debug.Log(MoveDirection());
        }
    }


}