You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.8 KiB
C#
62 lines
1.8 KiB
C#
using UnityEngine;
|
|
|
|
public class CameraHeadBobbing : MonoBehaviour
|
|
{
|
|
public float bobFrequency = 2f;
|
|
public float bobAmplitude = 0.05f;
|
|
public float swayAmplitude = 0.02f;
|
|
public float transitionSpeed = 5f;
|
|
|
|
public CharacterMovement movementScript; // Reference to your character movement
|
|
|
|
private Vector3 initialLocalPos;
|
|
private float timer;
|
|
public AudioClip footstepsClip;
|
|
private AudioSource audioSource;
|
|
|
|
void Awake()
|
|
{
|
|
audioSource = gameObject.AddComponent<AudioSource>();
|
|
audioSource.clip = footstepsClip;
|
|
audioSource.loop = true;
|
|
audioSource.playOnAwake = false;
|
|
}
|
|
|
|
void OnEnable()
|
|
{
|
|
if (footstepsClip != null && !audioSource.isPlaying)
|
|
audioSource.Play();
|
|
}
|
|
|
|
void OnDisable()
|
|
{
|
|
if (audioSource.isPlaying)
|
|
audioSource.Stop();
|
|
}
|
|
void Start()
|
|
{
|
|
initialLocalPos = transform.localPosition;
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
bool isWalking = movementScript != null && movementScript.state == CharacterMovement.MovementState.Walking;
|
|
|
|
if (isWalking)
|
|
{
|
|
timer += Time.deltaTime * bobFrequency;
|
|
|
|
float verticalOffset = Mathf.Sin(timer * Mathf.PI * 2f) * bobAmplitude;
|
|
float sideOffset = Mathf.Sin(timer * Mathf.PI) * swayAmplitude;
|
|
|
|
Vector3 targetOffset = new Vector3(sideOffset, verticalOffset, 0);
|
|
transform.localPosition = Vector3.Lerp(transform.localPosition, initialLocalPos + targetOffset, Time.deltaTime * transitionSpeed);
|
|
}
|
|
else
|
|
{
|
|
// Reset to original position smoothly
|
|
transform.localPosition = Vector3.Lerp(transform.localPosition, initialLocalPos, Time.deltaTime * transitionSpeed);
|
|
}
|
|
}
|
|
}
|