如何判断滑动方向是否与玩家前进方向一致?
问题描述
我现在通过滑动方向控制玩家移动,但希望只有当滑动方向与玩家前进方向一致时,才让玩家移动,逻辑大概是这样:
if (swipeDirection == myPlayersForwardDirection) { // 移动玩家 } else { // 不移动 }
但我不知道怎么比较滑动方向和玩家前进方向,以下是我当前的滑动检测代码:
// 类内变量 Vector2 firstPressPos; Vector2 secondPressPos; Vector2 currentSwipe; public void Swipe() { if(Input.GetMouseButtonDown(0)) { // 记录触摸开始的2D坐标 firstPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y); } if(Input.GetMouseButtonUp(0)) { // 记录触摸结束的2D坐标 secondPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y); // 计算滑动向量 currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y); // 归一化滑动向量 currentSwipe.Normalize(); // 检测向上滑动 if(currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) { Debug.Log("向上滑动"); } // 检测向下滑动 if(currentSwipe.y < 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) { Debug.Log("向下滑动"); } // 检测向左滑动 if(currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) { Debug.Log("向左滑动"); } // 检测向右滑动 if(currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) { Debug.Log("向右滑动"); } } }
解决方案
核心是把屏幕空间的滑动向量和玩家的前进方向转换到同一空间,再通过点积判断方向是否匹配(直接用==比较向量容易因为精度问题出错,点积更可靠)。
步骤1:定义玩家前进方向的屏幕空间向量
假设你的玩家是2D角色,前进方向是transform.up(如果是横向移动游戏,可换成transform.right,根据游戏实际坐标系调整),把它转换成屏幕空间的方向向量:
// 获取玩家前进方向的屏幕空间向量 Vector2 GetPlayerForwardScreenDirection() { // 把世界空间的前进方向转换为屏幕空间的方向(从相机视角出发) Vector3 worldForward = transform.up; // 替换为你的玩家实际前进方向 Vector3 screenForward = Camera.main.WorldToScreenPoint(transform.position + worldForward) - Camera.main.WorldToScreenPoint(transform.position); return new Vector2(screenForward.x, screenForward.y).normalized; }
步骤2:修改滑动检测逻辑,加入方向匹配判断
在滑动结束后,计算滑动向量和玩家屏幕前进方向的点积,当点积大于设定的阈值(比如0.7,对应两个向量夹角在45度以内),就认为方向一致,触发移动:
public void Swipe() { if(Input.GetMouseButtonDown(0)) { firstPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y); } if(Input.GetMouseButtonUp(0)) { secondPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y); currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y); currentSwipe.Normalize(); // 获取玩家前进的屏幕方向 Vector2 playerForwardScreen = GetPlayerForwardScreenDirection(); // 计算点积,判断方向是否一致 float dotProduct = Vector2.Dot(currentSwipe, playerForwardScreen); // 阈值0.7对应约45度的容错范围,可根据需求调整 if(dotProduct > 0.7f) { Debug.Log("滑动方向与玩家前进方向一致,开始移动"); // 这里写入你的玩家移动逻辑,例如: // transform.Translate(transform.up * moveSpeed * Time.deltaTime); } else { Debug.Log("滑动方向与玩家前进方向不符,不移动"); } } }
关键说明
- 点积的取值范围是
[-1,1]:1表示两个向量完全同向,-1完全反向,0垂直。设置阈值(比如0.7)可以给滑动方向一定的容错空间,避免玩家必须完全精准滑动。 - 如果是3D游戏,只需要把玩家前进方向换成
transform.forward,然后同样转换到屏幕空间即可。 - 如果你的游戏是固定视角(比如顶视角),也可以直接把玩家的世界空间方向转换成2D平面的向量,和滑动向量在世界空间比较,无需转屏幕空间。
内容的提问来源于stack exchange,提问作者Sannan Ch
相关产品推荐
相关产品推荐

