Unity摇杆水平旋转相机报错:无法从Vector3转换为Space
问题解决:摇杆控制相机水平旋转的类型错误
错误原因
你调用的transform.Rotate(Vector3.up, ...)重载要求第二个参数是浮点型的旋转角度,但你传入的direction * rotationSpeed * Time.deltaTime是Vector3类型,类型不匹配导致报错。之前用键盘输入时传的horizontalInput * ...是浮点值,所以能正常运行。
解决方法
要实现相机水平旋转,只需要用到摇杆的水平轴输入(variableJoystick.Horizontal),不需要合成Vector3方向。因为水平旋转是绕Y轴(Vector3.up)旋转,旋转角度由水平输入的正负和大小决定。
修改后的Update方法代码:
void Update() { float horizontalInput = variableJoystick.Horizontal; // 绕Y轴(垂直向上)旋转,角度由水平输入、速度和帧时间决定 transform.Rotate(Vector3.up, horizontalInput * rotationSpeed * Time.deltaTime); }
完整修改后的脚本
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RotateCamera : MonoBehaviour { public float rotationSpeed = 50.0f; public VariableJoystick variableJoystick; void Start() { } void Update() { float horizontalInput = variableJoystick.Horizontal; transform.Rotate(Vector3.up, horizontalInput * rotationSpeed * Time.deltaTime); } }
补充(若需同时控制水平+垂直旋转)
如果之后需要同时用摇杆控制水平和垂直旋转,可以分开处理两个轴:
void Update() { float horizontalInput = variableJoystick.Horizontal; float verticalInput = variableJoystick.Vertical; // 水平旋转(绕Y轴) transform.Rotate(Vector3.up, horizontalInput * rotationSpeed * Time.deltaTime); // 垂直旋转(绕X轴,注意限制角度避免过度翻转) transform.Rotate(Vector3.right, verticalInput * rotationSpeed * Time.deltaTime); }
内容的提问来源于stack exchange,提问作者saqib
相关产品推荐
相关产品推荐

