54 lines
1.4 KiB
C#
54 lines
1.4 KiB
C#
using UnityEngine;
|
|
|
|
public class CameraShake : MonoBehaviour
|
|
{
|
|
public static CameraShake Instance { get; private set; }
|
|
|
|
private float shakeDuration = 0f;
|
|
private float shakeIntensity = 0f;
|
|
private float shakeFalloff = 1f;
|
|
|
|
private Vector3 originalLocalPos;
|
|
private bool shaking = false;
|
|
|
|
void Awake()
|
|
{
|
|
Instance = this;
|
|
originalLocalPos = transform.localPosition;
|
|
}
|
|
|
|
void LateUpdate()
|
|
{
|
|
if (!shaking) return;
|
|
|
|
if (shakeDuration > 0f)
|
|
{
|
|
Vector3 offset = Random.insideUnitSphere * shakeIntensity;
|
|
offset.z = 0f; // Keep shake on X/Y only
|
|
transform.localPosition = originalLocalPos + offset;
|
|
|
|
shakeDuration -= Time.deltaTime;
|
|
shakeIntensity = Mathf.Lerp(shakeIntensity, 0f, Time.deltaTime * shakeFalloff);
|
|
}
|
|
else
|
|
{
|
|
shaking = false;
|
|
shakeDuration = 0f;
|
|
transform.localPosition = originalLocalPos;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Trigger a camera shake.
|
|
/// </summary>
|
|
/// <param name="duration">How long to shake (seconds)</param>
|
|
/// <param name="intensity">How far to displace the camera</param>
|
|
public void Shake(float duration, float intensity)
|
|
{
|
|
shakeDuration = duration;
|
|
shakeIntensity = intensity;
|
|
shakeFalloff = intensity / duration;
|
|
shaking = true;
|
|
}
|
|
}
|