[unity]如何判断鼠标/触摸滑动方向
PC端跟手机端都可以用
效果为从屏幕上任意位置向其他位置滑动的时候,检测滑动方向,这里只写了上下左右四方向,一般情况下也够用了
Vector2 lastPos;//鼠标上次位置
Vector2 currPos;//鼠标当前位置
Vector2 offset;//两次位置的偏移值
void Update()
{
if (Input.GetMouseButtonDown(0))
{
lastPos = Input.mousePosition;
}
if (Input.GetMouseButtonUp(0))
{
currPos = Input.mousePosition;
offset = currPos - lastPos;
DoMatch(offset);
}
}
void DoMatch(Vector2 _offset)
{
//水平移动
if (Mathf.Abs(offset.x) > Mathf.Abs(offset.y))
{
if (offset.x > 0)
{
Debug.Log("右");
}
else
{
Debug.Log("左");
}
}
else//垂直移动
{
if (offset.y > 0)
{
Debug.Log("上");
}
else
{
Debug.Log("下");
}
}
}