본문 바로가기

Game/Unity

[unity3d] swipe

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");
            }
        }
    }
}