unity 手指上下左右滑动的判定


可能游戏中需要进行手指滑动的判定,


例如,向左滑动,向上滑动,


最常见的就是跑酷游戏中的动作。


我写了一个简单的处理方式,跟大家分享一下。


using UnityEngine;
using System.Collections;

public class jarodInputController : MonoBehaviour {


private float fingerActionSensitivity = Screen.width * 0.05f; //手指动作的敏感度,这里设定为 二十分之一的屏幕宽度.
//
private float fingerBeginX;
private float fingerBeginY;
private float fingerCurrentX;
private float fingerCurrentY;
private float fingerSegmentX;
private float fingerSegmentY;
//
private int fingerTouchState;
//
private int FINGER_STATE_NULL = 0;
private int FINGER_STATE_TOUCH = 1;
private int FINGER_STATE_ADD = 2;
// Use this for initialization
void Start () 
{
fingerActionSensitivity = Screen.width * 0.05f;

fingerBeginX = 0;
fingerBeginY = 0;
fingerCurrentX = 0;
fingerCurrentY = 0;
fingerSegmentX = 0;
fingerSegmentY = 0;

fingerTouchState = FINGER_STATE_NULL;
}
// Update is called once per frame
void Update ()
{

if (Input.GetKeyDown (KeyCode.Mouse0)) 
{

if(fingerTouchState == FINGER_STATE_NULL)
{
fingerTouchState = FINGER_STATE_TOUCH;
fingerBeginX = Input.mousePosition.x;
fingerBeginY = Input.mousePosition.y;
}

}

if(fingerTouchState == FINGER_STATE_TOUCH)
{
fingerCurrentX = Input.mousePosition.x;
fingerCurrentY = Input.mousePosition.y;
fingerSegmentX = fingerCurrentX - fingerBeginX;
fingerSegmentY = fingerCurrentY - fingerBeginY;

}


if (fingerTouchState == FINGER_STATE_TOUCH) 
{
float fingerDistance = fingerSegmentX*fingerSegmentX + fingerSegmentY*fingerSegmentY; 

if (fingerDistance > (fingerActionSensitivity*fingerActionSensitivity))
{
toAddFingerAction();
}
}

if (Input.GetKeyUp(KeyCode.Mouse0))
{
fingerTouchState = FINGER_STATE_NULL;
}
}

private void toAddFingerAction()
{

fingerTouchState = FINGER_STATE_ADD;

if (Mathf.Abs (fingerSegmentX) > Mathf.Abs (fingerSegmentY)) 
{
fingerSegmentY = 0;
else 
{
fingerSegmentX = 0;
}

if (fingerSegmentX == 0) 
{
if (fingerSegmentY > 0) 
{
Debug.Log ("up");
else {
Debug.Log ("down");
}
else if(fingerSegmentY == 0) 
{
if(fingerSegmentX > 0)
{
Debug.Log ("right");
}
else
{
Debug.Log("left");
}
}

}
}

上面的代码,可以直接在控制台中,看到运行的结果,


如果感觉还可以,那么就在打印语句的部分,替换成自己想要的具体代码,


可能这个响应是主动的,


也有可能这个响应是被动的,


主动和被动就好像是快递,


一种是快递把你买的东西送到你的公司,直接打电话给你,你到公司门口去取,


这种方式,就像是主动的。


一种是快递把你买的东西送到你的公司,交给前台,前台统一放到一个地方,


可能你中午吃饭的时候,会去看看有没有自己的快递,


这种方式,就像是被动的。


一种要求立刻响应,一种什么时候响应是你说了算。



你可能感兴趣的:(unity)