判断方向

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


public class TouchMove : MonoBehaviour {
    private Swipe swipe;
    private Direction dir;
    public Text text;
	
	// Update is called once per frame
	void Update () {
        //pc平台
#if UNITY_STANDALONE
        //鼠标按下记录初始位置
        if (Input.GetMouseButtonDown(0))
        {
            swipe = new Swipe();
            swipe.start_point = Input.mousePosition;
        }
        //记录结束位置,如果和开始位置距离大于等于屏幕宽度的四分之一,分析方向
        if (Input.GetMouseButton(0))
        {
            swipe.end_point = Input.mousePosition;
            if (Vector2.Distance(swipe.start_point,swipe.end_point)>=Screen.width/4)
            {
                Analysis(swipe);
                text.text = dir.ToString();
            }
        }
        //鼠标抬起的话清空记录
        if (Input.GetMouseButtonUp(0))
        {
            swipe = null;
        }
#endif
        //安卓平台下
#if UNITY_ANDROID
        for (int i = 0; i < Input.touchCount; i++)
        {
            Touch t = Input.GetTouch(0);
            if (t.phase==TouchPhase.Began)
            {
                swipe = new Swipe();
                swipe.start_point = t.position;
            }
            if (t.phase == TouchPhase.Moved|| t.phase == TouchPhase.Stationary)
            {
                swipe.end_point = t.position;
                if (Vector2.Distance(swipe.start_point, swipe.end_point) >= Screen.width / 4)
                {
                    Analysis(swipe);
                    text.text = dir.ToString();
                }
            }
            if (t.phase == TouchPhase.Ended)
            {
                swipe = null;
            }
        }
#endif
    }
    /// <summary>
    /// 根据开始位置和结束位置分析并返回方向
    /// </summary>
    /// <param name="swipe"></param>
    /// <returns></returns>
    private Direction Analysis(Swipe swipe)
    {
        Vector2 v2 = swipe.end_point - swipe.start_point;
        v2 = v2.normalized;
        float max = 0;
        if (Vector2.Dot(v2,Vector2.up)>max)
        {
            max = Vector2.Dot(v2, Vector2.up);
            dir= Direction.Up;
        }
        if (Vector2.Dot(v2, Vector2.down) > max)
        {
            max = Vector2.Dot(v2, Vector2.down);
            dir = Direction.Down;
        }
        if (Vector2.Dot(v2, Vector2.right) > max)
        {
            max = Vector2.Dot(v2, Vector2.right);
            dir = Direction.Right;
        }
        if (Vector2.Dot(v2, Vector2.left) > max)
        {
            max = Vector2.Dot(v2, Vector2.left);
            dir = Direction.Left;
        }
        return dir;
    }
}
/// <summary>
/// 记录开始位置和结束位置
/// </summary>
public class Swipe
{
    public Vector2 start_point;
    public Vector2 end_point;
}
/// <summary>
/// 枚举上下左右四个方向
/// </summary>
public enum Direction
{
    None,
    Right,
    Left,
    Down,
    Up
}

猜你喜欢

转载自blog.csdn.net/qq_41692884/article/details/85237591