using UnityEngine;
///
/// Mouse-look yaw/pitch accumulator with optional SmoothDampAngle smoothing, shared by the
/// first-person and freecam rigs. accumulates a scaled mouse delta into the
/// target angles and advances the smoothed display angles; seeds everything
/// from an existing rotation so going live produces no visible jump.
///
public struct SmoothedLook
{
float _yaw; // look target (raw input accumulates here)
float _pitch;
float _displayYaw; // smoothed value actually applied to the transform
float _displayPitch;
float _yawSmoothRef;
float _pitchSmoothRef;
/// Smoothed yaw shown this frame (drives the body's facing in first person).
public float DisplayYaw => _displayYaw;
/// Rotation composed from the smoothed display angles.
public Quaternion Rotation => Quaternion.Euler(_displayPitch, _displayYaw, 0f);
/// Accumulates one frame of look input and advances the smoothed display angles.
public void Tick(Vector2 scaledDelta, float hSens, float vSens, bool invertY, float maxPitch, float smoothTime)
{
_yaw += scaledDelta.x * hSens;
float vs = vSens * (invertY ? 1f : -1f);
_pitch = Mathf.Clamp(_pitch + scaledDelta.y * vs, -maxPitch, maxPitch);
if (smoothTime > 0f)
{
// SmoothDampAngle is frame-rate-independent and wraps yaw correctly.
_displayYaw = Mathf.SmoothDampAngle(_displayYaw, _yaw, ref _yawSmoothRef, smoothTime);
_displayPitch = Mathf.SmoothDampAngle(_displayPitch, _pitch, ref _pitchSmoothRef, smoothTime);
}
else
{
_displayYaw = _yaw;
_displayPitch = _pitch;
}
}
/// Seeds the look angles from an existing rotation, then snaps the smoothed state to them.
public void SyncTo(Quaternion rotation, float maxPitch)
{
Vector3 e = rotation.eulerAngles;
_yaw = e.y;
float p = e.x > 180f ? e.x - 360f : e.x;
_pitch = Mathf.Clamp(p, -maxPitch, maxPitch);
Snap();
}
/// Snaps the smoothed state to the current targets so entering never lags/jumps to catch up.
public void Snap()
{
_displayYaw = _yaw;
_displayPitch = _pitch;
_yawSmoothRef = 0f;
_pitchSmoothRef = 0f;
}
}