Swipe 판별

Unity/스크립트 2015. 7. 20. 21:45

using UnityEngine;
using System.Collections;

public class Swipe : MonoBehaviour
{
    // const
    public const string RIGHT = "Right";
    public const string DOWN = "Down";
    public const string LEFT = "Left";
    public const string UP = "Up";
    // delegate
    public delegate void SwapeDelegate (string way);

    public SwapeDelegate swape {
        set {
            swapeDelegate = value;
        }
    }

    private SwapeDelegate swapeDelegate;
    // variable
    private Vector2 touchStartPos;
    private bool touchStarted;
    private float minSwipeDistancePixels = 100f;

    void Update ()
    {
        if (Input.touchCount > 0) {
            var touch = Input.touches [0];
            
            switch (touch.phase) {
            case TouchPhase.Began:
                touchStarted = true;
                touchStartPos = touch.position;
                break;
            case TouchPhase.Ended:
                if (touchStarted) {
                    Swipe (touch);
                    touchStarted = false;
                }
                break;
            case TouchPhase.Canceled:
                touchStarted = false;
                break;
            case TouchPhase.Stationary:
                break;
            case TouchPhase.Moved:
                break;
            }
        }
    }

    private void Swipe (Touch touch)
    {
        var lastPos = touch.position;
        var distance = Vector2.Distance (lastPostouchStartPos);
        
        if (distance > minSwipeDistancePixels) {
            float dy = lastPos.y - touchStartPos.y;
            float dx = lastPos.x - touchStartPos.x;
            
            float angle = Mathf.Rad2Deg * Mathf.Atan2 (dxdy);
            
            angle = (360 + angle - 45) % 360;

            if (angle < 90) {
                // right
                swapeDelegate ("Left");
            } else if (angle < 180) {
                // down
                swapeDelegate ("Down");
            } else if (angle < 270) {
                // left
                swapeDelegate ("Right");
            } else {
                // up
                swapeDelegate ("Up");
            }
        }
    }
}


출처 - http://seungngil.tistory.com/

'Unity > 스크립트' 카테고리의 다른 글

Reactive Extension  (0) 2015.12.11
Raycast시 원하는 충돌레이어 지정  (0) 2015.10.16
Android 국가코드 정보  (0) 2015.06.07
에셋 Android Native Plugins에 대해  (0) 2015.03.02
String -> enum 변환  (0) 2015.02.17

WRITTEN BY
빨강꼬마

,