본문 바로가기

유니티, C#

마우스 스와이프 구현 로직

    private Vector3 m_firstPosition;
    private Vector3 m_lastPosition;

    private float m_angle;
    private float swipeResist = 1f;

	private void OnMouseDown()
    {
        m_firstPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }

    private void OnMouseUp()
    {
        m_lastPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        CalculateAngle();
    }

    private void CalculateAngle()
    {
        if (Mathf.Abs(m_lastPosition.y - m_firstPosition.y) > swipeResist
            || Mathf.Abs(m_lastPosition.x - m_firstPosition.x) > swipeResist)
        {
            // Polar Coordinates
            m_angle = Mathf.Atan2(m_lastPosition.y - m_firstPosition.y, m_lastPosition.x - m_firstPosition.x) * 180 / Mathf.PI;
        }
    }

 

OnMouseDown()은 사용자가 GUIElement 또는 Collider위에서 마우스 버튼을 누른 경우에, 호출된다.

눌렀을 때의 위치를 m_firstPosition 변수에 저장한다.

 

OnMouseUp()은 사용자가 마우스 버튼 클릭을 해제했을 때 호출된다.

해당 위치를 m_lastPosition 변수에 저장하고 CalculateAngle() 함수를 호출한다.

 

CalculateAngle()은 m_firstPosition과 m_lastPosition의 각도를 측정한다.

마지막 위치와 첫번째 위치의 x값 또는 y값 거리를 측정한 후 기준거리(swipeResist, 1f) 이상인지 확인한다.

기준거리 이상이라면 극좌표계를 사용한다. Atan2() 함수를 이용하여 수평축으로부터의 거리를 구한 후, radian 값으로 변환한다.

 

극 좌표계는 여기있는 설명으로 공부했다.

https://choryeonworkshop.tistory.com/124

 

+ OnMouseDown(), OnMouseUp()이 호출되려면 해당 오브젝트는 콜라이더를 가져야한다

'유니티, C#' 카테고리의 다른 글

스크롤뷰 최적화 (RectMask2D)  (0) 2020.03.19
클래스, 추상 클래스, 인터페이스 비교  (0) 2020.02.16