跟随Brackeys教程实现鼠标视角控制时代码失效求助
问题解决:鼠标视角控制代码修复
核心错误修复
你的代码里存在一个语法错误,直接导致视角横向旋转失效:
- 错误点:
playerBody.Rotate=(Vector3.up * mouseX);Rotate是Transform类的方法,不是可赋值属性,必须以方法调用的形式使用:playerBody.Rotate(Vector3.up * mouseX);
额外验证事项
除了语法修复,还需要确认以下配置是否正确:
- 脚本挂载位置:该
Mouse_Look脚本必须挂载在主相机上 - playerBody赋值:在Inspector面板中,将玩家对象(比如第一人称的Capsule)的Transform拖入
playerBody字段 - 灵敏度调整:如果视角转动速度不符合预期,可以微调
mousesen的数值(默认100f为适中值)
修复后的完整代码
using UnityEngine; public class Mouse_Look : MonoBehaviour { public float mousesen = 100f; public Transform playerBody; float xRotation = 0f; void Start() { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } void Update() { float mouseX = Input.GetAxis("Mouse X") * Time.deltaTime * mousesen; float mouseY = Input.GetAxis("Mouse Y") * Time.deltaTime * mousesen; xRotation -= mouseY; xRotation = Mathf.Clamp(xRotation, -90f, 90f); transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f); playerBody.Rotate(Vector3.up * mouseX); } }
内容的提问来源于stack exchange,提问作者Ashitosh bendre
相关产品推荐
相关产品推荐

