my-unity-assets / Assets /Scripts /PlayerCamController.cs
AliAch's picture
Add wall-sticking yaw clamp 200 deg on each directions
72180aa
Raw History Blame Contribute Delete
2.78 kB
using UnityEngine;
public class PlayerCamController : MonoBehaviour
{
[Header("Sensitivity Settings")]
[SerializeField] private float sensX = 400f;
[SerializeField] private float sensY = 400f;
[Header("References")]
[SerializeField] private Transform playerOrient;
[SerializeField] private Transform camHolder;
[Tooltip("Used to detect wall-sticking so yaw can be clamped while stuck to a wall. Auto-found in scene if left empty.")]
[SerializeField] private PlayerMovement playerMovement;
[Header("Wall Stick Yaw Clamp")]
[Tooltip("How far (degrees) the player can turn left/right of the yaw they were facing when they stuck to the wall.")]
[SerializeField] private float wallStickYawClampRange = 200f;
private float rotXCam;
private float rotYCam;
private bool wasWallSticking;
private float wallStickYawAnchor;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
if (playerMovement == null) playerMovement = FindObjectOfType<PlayerMovement>();
// Cache the current rotation angles on startup so no snap to 0
if (camHolder != null)
{
Vector3 currentRotation = camHolder.eulerAngles;
// Normalize angles
rotXCam = currentRotation.x;
if (rotXCam > 180) rotXCam -= 360f;
rotYCam = currentRotation.y;
}
}
private void Update()
{
float mouseX = Input.GetAxisRaw("Mouse X") * sensX * Time.deltaTime;
float mouseY = Input.GetAxisRaw("Mouse Y") * sensY * Time.deltaTime;
rotYCam += mouseX;
rotXCam -= mouseY;
rotXCam = Mathf.Clamp(rotXCam, -80f, 80f);
HandleWallStickYawClamp();
// Rotate the HOLDER instead of the camera child to maintain the pivot
if (camHolder != null)
{
camHolder.rotation = Quaternion.Euler(rotXCam, rotYCam, 0);
}
// Rotate player body orientation on Y axis
if (playerOrient != null)
{
playerOrient.rotation = Quaternion.Euler(0, rotYCam, 0);
}
}
private void HandleWallStickYawClamp()
{
if (playerMovement == null) return;
bool isSticking = playerMovement.IsWallSticking;
// Just started sticking this frame - anchor the clamp to the current facing.
if (isSticking && !wasWallSticking)
{
wallStickYawAnchor = rotYCam;
}
if (isSticking)
{
float min = wallStickYawAnchor - wallStickYawClampRange;
float max = wallStickYawAnchor + wallStickYawClampRange;
rotYCam = Mathf.Clamp(rotYCam, min, max);
}
wasWallSticking = isSticking;
}
}