如何实现类人类头部的相机旋转限制(附Player相机控制器代码)
Add Human-Like Camera Rotation Limits to Your Player Controller
Got it, let's tweak your existing controladortrajeCamLibre method to add realistic rotation limits that mimic how a human head moves—no more 360-degree backflips with the camera! Here's the modified code and breakdown:
First, add these public variables to your class (so you can adjust them directly in the Unity Inspector without touching code):
// Pitch (up/down) limits - adjust these to match your desired head movement range public float maxLookUpAngle = 60f; // Max angle to look upward public float maxLookDownAngle = 45f; // Max angle to look downward // Optional: Yaw (left/right) limit for body rotation public float maxTurnAngle = 180f; // Max rotation left/right from initial position private float initialYRotation; // Stores the character's starting Y rotation
Then initialize the initial rotation in your Start() method:
void Start() { // Save the character's starting Y rotation to use as our reference point initialYRotation = character.transform.localEulerAngles.y; }
Now update your controladortrajeCamLibre method to apply the limits:
public void controladortrajeCamLibre() { // Original camera input handling Vector2 md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")); md = Vector2.Scale(md, new Vector2(sensitivity * smothing, sensitivity * smothing)); smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1.0f / smothing); smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1.0f / smothing); mouseLook += smoothV; // 1. Limit pitch (up/down) rotation to human-like range mouseLook.y = Mathf.Clamp(mouseLook.y, -maxLookDownAngle, maxLookUpAngle); // 2. Optional: Limit yaw (left/right) body rotation float targetYRotation = initialYRotation + mouseLook.x; targetYRotation = Mathf.Clamp(targetYRotation, initialYRotation - maxTurnAngle, initialYRotation + maxTurnAngle); character.transform.localRotation = Quaternion.Euler(0f, targetYRotation, 0f); // Apply the clamped rotation to the camera cam.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right); }
What's changed:
- Pitch Limits:
Mathf.ClamplocksmouseLook.ybetween-maxLookDownAngleandmaxLookUpAngle. This stops the camera from flipping all the way up or down—matches how a person can't look straight up or down beyond a natural range. - Optional Yaw Limits: We track the character's starting rotation and clamp any left/right turn to stay within
maxTurnAngleof that position. If you don't need this (e.g., you want the player to spin freely), just remove this section. - Simplified Body Rotation: Switched from
Quaternion.AngleAxistoQuaternion.Eulerfor the character's rotation—it's easier to work with and clamp Y-axis values this way.
内容的提问来源于stack exchange,提问作者jesus _
相关产品推荐
相关产品推荐

