Unity角色/相机移动失控问题求助
Unity角色移动与相机控制故障求助:相机转向超90度后角色失控旋转
我正在Unity中开发游戏,跟随Dapper Dino教程实现角色移动与相机控制功能,大部分小问题已解决,但当相机左右转动超过90度时,角色会失控旋转。尝试了该视频评论区的多种方案均无效,以下是相关代码及问题说明,恳请提供帮助。
角色移动代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovementController : MonoBehaviour { [SerializeField] private float speed; [SerializeField] private float jumpForce; [SerializeField] private float JumpraycastDistance; private Rigidbody rb; private void Start() { rb = GetComponent<Rigidbody>(); } private void Update() { Jump(); } private void FixedUpdate() { Move(); } private void Move() { float hAxis = Input.GetAxisRaw("Horizontal"); float vAxis = Input.GetAxisRaw("Vertical"); Vector3 movement = new Vector3(hAxis, 0, vAxis) * speed * Time.fixedDeltaTime; Vector3 newPosition = rb.position + rb.transform.TransformDirection(movement); rb.MovePosition(newPosition); } private void Jump() { if(Input.GetKeyDown(KeyCode.Space)) { if (IsGrounded()) { rb.AddForce(0, jumpForce, 0, ForceMode.Impulse); } } } private bool IsGrounded() { return Physics.Raycast(transform.position, Vector3.down, JumpraycastDistance); } }
相机控制代码
using UnityEngine; public class CameraController : MonoBehaviour { [SerializeField] private float lookSensitivity; [SerializeField] private float smoothing; private GameObject player; private Vector2 smoothedVelocity; private Vector2 currentLookingPos; private void Start() { player = transform.parent.gameObject; Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } private void Update() { RotateCamera(); CheckForShooting(); } private void RotateCamera() { Vector2 inputeValues = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")); inputeValues = Vector2.Scale(inputeValues, new Vector2(lookSensitivity * smoothing, lookSensitivity * smoothing)); smoothedVelocity.x = Mathf.Lerp(smoothedVelocity.x, inputeValues.x, 1f / smoothing); smoothedVelocity.y = Mathf.Lerp(smoothedVelocity.y, inputeValues.y, 1f / smoothing); currentLookingPos += smoothedVelocity; currentLookingPos.y = Mathf.Clamp(currentLookingPos.y, -80f, 80f); transform.localRotation = Quaternion.AngleAxis(-currentLookingPos.y, Vector3.right); player.transform.localRotation = Quaternion.AngleAxis(currentLookingPos.x, player.transform.up); } private void CheckForShooting() { // 原代码未实现该方法,保留空方法占位 } }
问题说明
当相机左右转动角度超过90度时,角色会出现不受控制的异常旋转,无法正常保持移动方向与相机视角的匹配。
内容的提问来源于stack exchange,提问作者user15500238
相关产品推荐
相关产品推荐

