[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("下");
}
}
}