Unity中3D角色触摸移动实现失败,现有代码无效求解决
3D角色触摸移动问题修复
我有一个简单的3D角色,希望通过触摸操作使其在场景中移动,需求为实时根据玩家手部的前后滑动位置计算移动方向向量,但编写的以下两个类并未解决问题。
原触摸控制类代码
void Update() { if (Input.touchCount == 1) { PlayerTouch = Input.GetTouch(0); if (PlayerTouch.phase == TouchPhase.Moved) { MoveDirection.x = TouchDeltaPosition.x; MoveDirection.z = TouchDeltaPosition.y; } characterMove.Move(MoveDirection * 1000); }
原CharacterMove类代码
public void Move(Vector3 moveDirecion) { transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(moveDirecion), Time.deltaTime * Speed); transform.position += transform.forward*Time.deltaTime * Speed2; }
问题分析
- 触摸控制类问题:
- 错误直接使用
TouchDeltaPosition,应调用触摸对象的deltaPosition属性(即PlayerTouch.deltaPosition) - 仅在
TouchPhase.Moved时更新方向,但触摸静止/结束时未重置MoveDirection,导致角色持续移动 - 1000的放大系数过大,会让方向向量异常,引发旋转和移动混乱
- 错误直接使用
- CharacterMove类问题:
- 直接使用原始方向向量执行
LookRotation,若向量过小或包含y轴分量,会导致角色旋转异常(比如看向世界原点) - 无论是否有有效输入,角色都会沿
transform.forward移动,不符合触摸控制逻辑
- 直接使用原始方向向量执行
修复后的代码
触摸控制类
private Vector3 MoveDirection; void Update() { MoveDirection = Vector3.zero; // 每次帧重置方向,避免残留输入 if (Input.touchCount == 1) { var playerTouch = Input.GetTouch(0); switch (playerTouch.phase) { case TouchPhase.Moved: // 将屏幕触摸增量转换为世界空间方向,缩小系数避免数值过大 MoveDirection.x = playerTouch.deltaPosition.x * 0.01f; MoveDirection.z = playerTouch.deltaPosition.y * 0.01f; break; case TouchPhase.Ended: case TouchPhase.Canceled: MoveDirection = Vector3.zero; // 触摸结束时停止移动 break; } } characterMove.Move(MoveDirection); }
CharacterMove类
public float RotateSpeed = 8f; // 旋转速度,可在Inspector调整 public float MoveSpeed = 5f; // 移动速度,可在Inspector调整 public void Move(Vector3 moveDirection) { // 仅当方向向量有效时执行旋转和移动 if (moveDirection.magnitude > 0.01f) { // 过滤y轴分量,确保角色仅在水平面上旋转 var targetDirection = new Vector3(moveDirection.x, 0f, moveDirection.z).normalized; // 平滑旋转朝向目标方向 transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(targetDirection), Time.deltaTime * RotateSpeed); // 沿朝向方向移动 transform.position += transform.forward * Time.deltaTime * MoveSpeed; } }
修复说明
- 触摸控制类:确保每次帧重置方向,正确获取触摸增量,处理触摸结束状态,合理缩小方向系数
- CharacterMove类:仅在有有效输入时执行动作,过滤y轴避免异常旋转,使用可调整的速度变量提升灵活性
内容的提问来源于stack exchange,提问作者galaxy studio
相关产品推荐
相关产品推荐

