我是靠谱客的博主 欢呼万宝路,这篇文章主要介绍Unity中实现一个手势输入判断方向的小功能,现在分享给大家,希望可以做个参考。

Unity中实现通过滑动屏幕,判断当前的手势是向上、下、左、右哪个方向滑动。


思路
如下图所示,原点为起始点,箭头位置为手势滑动结束的位置,分别X轴方向和Y轴方向的数值进行比较,如果X的绝对值大于Y的绝对值,则是左右方向上的移动。如果该向量大于0则向右移动,反之小于0则向左移动。其余方向上的判断同理。
在这里插入图片描述
代码如下:
定义一个枚举,记录方向。

复制代码
1
2
3
4
5
6
7
8
9
public enum InputDirection { NULL, //空 Right, //右 Left, //左 Down, //下 Up //上 }

用户手势判定代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
bool activeInput=false; //手势的标志位 Vector3 m_mousePos; //记录位置 void UserInput() { m_inputDir = InputDirection.NULL; if (Input.GetMouseButtonDown(0)) { activeInput = true; m_mousePos = Input.mousePosition; } //滑动 if (Input.GetMouseButton(0)&activeInput) { Vector3 Dir = Input.mousePosition - m_mousePos; if (Dir.magnitude>20) { if (Mathf.Abs(Dir.x)>Mathf.Abs(Dir.y)&&Dir.x>0) { m_inputDir = InputDirection.Right; } else if (Mathf.Abs(Dir.x) > Mathf.Abs(Dir.y) && Dir.x < 0) { m_inputDir = InputDirection.Left; } else if (Mathf.Abs(Dir.x) < Mathf.Abs(Dir.y) && Dir.y > 0) { m_inputDir = InputDirection.Up; } else if (Mathf.Abs(Dir.x) < Mathf.Abs(Dir.y) && Dir.x < 0) { m_inputDir = InputDirection.Down; } activeInput = false; } } //打印测试 print(m_inputDir); }

最后

以上就是欢呼万宝路最近收集整理的关于Unity中实现一个手势输入判断方向的小功能的全部内容,更多相关Unity中实现一个手势输入判断方向内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部