Files
Stair_Horror/Assets/Scripts/HeadBobber.cs

44 lines
1.4 KiB
C#

using UnityEngine;
public class HeadBobber : MonoBehaviour
{
[Header("Settings")]
public float bobSpeed = 14f; // How fast the head bobs
public float bobAmount = 0.05f; // How high/low the head goes
[Tooltip("Reference to the parent player object")]
public CharacterController playerController;
private float defaultPosY = 0;
private float timer = 0;
void Start()
{
// Remember where the camera is supposed to be normally
defaultPosY = transform.localPosition.y;
}
void Update()
{
if (playerController == null) return;
// Only bob if we are moving roughly walking speed
// (magnitude > 0.1f) means we are moving
if (Mathf.Abs(playerController.velocity.x) > 0.1f || Mathf.Abs(playerController.velocity.z) > 0.1f)
{
// Calculate the Sine Wave
timer += Time.deltaTime * bobSpeed;
float newY = defaultPosY + Mathf.Sin(timer) * bobAmount;
// Apply it
transform.localPosition = new Vector3(transform.localPosition.x, newY, transform.localPosition.z);
}
else
{
// Reset to neutral when stopped
timer = 0;
Vector3 targetPos = new Vector3(transform.localPosition.x, defaultPosY, transform.localPosition.z);
transform.localPosition = Vector3.Lerp(transform.localPosition, targetPos, Time.deltaTime * 5f);
}
}
}