使用Unity自带的Input类实现简单的手势识别。其原理是使用向量点乘计算鼠标按下去的点和抬起点的向量,和上下左右方向之间的角度,如果角度小于45°或-45°则认为是该方向。跑酷游戏中使用。
Vector3 mousePos;
bool activeInput;//手势识别使用
void GetInputDirection() {
inputDirection = InputDirection.NULL;
if (Input.GetMouseButtonDown(0))
{
activeInput = true;
mousePos = Input.mousePosition;
}
if (Input.GetMouseButton(0)&&activeInput)
{
Vector3 vec = Input.mousePosition - mousePos;
if (vec.magnitude>20)
{
float angleYFloat = Vector3.Dot(Vector3.up, vec.normalized);
float angleY = Mathf.Acos(angleYFloat) * Mathf.Rad2Deg;
float angleXFloat = Vector3.Dot(Vector3.right, vec.normalized);
float angleX = Mathf.Acos(angleXFloat) * Mathf.Rad2Deg;
if (angleY <= 45)
{
inputDirection = InputDirection.Up;
}
else if (angleY>=135)
{
inputDirection = InputDirection.Down;
}
else if (angleX < 45)
{
inputDirection = InputDirection.Right;
}
else if(angleX >= 135)
{
inputDirection = InputDirection.Left;
}
// Debug.Log(inputDirection);
activeInput = false;
}
}
}