57 lines
1.6 KiB
C#
57 lines
1.6 KiB
C#
using System.Collections;
|
|
using UnityEngine;
|
|
using Cinemachine; // Ensure you have the Cinemachine namespace
|
|
|
|
public class CameraShaker : MonoBehaviour
|
|
{
|
|
public static CameraShaker Instance;
|
|
public CinemachineCameraOffset offsetter;
|
|
|
|
// Variables for tracking shake duration and original offset
|
|
private Vector3 originalOffset;
|
|
private Coroutine shakeCoroutine;
|
|
|
|
private void Awake()
|
|
{
|
|
if (Instance == null)
|
|
{
|
|
Instance = this;
|
|
originalOffset = new Vector3(0, 0, 0); // Initialize with your default offset
|
|
}
|
|
else
|
|
{
|
|
Destroy(gameObject);
|
|
}
|
|
|
|
offsetter = GetComponent<CinemachineCameraOffset>();
|
|
}
|
|
|
|
public static void ShakecShake(float strength, float time)
|
|
{
|
|
// Check if a shake is already happening and restart it if so
|
|
if (Instance.shakeCoroutine != null)
|
|
{
|
|
Instance.StopCoroutine(Instance.shakeCoroutine);
|
|
}
|
|
Instance.shakeCoroutine = Instance.StartCoroutine(Instance.DoShake(strength, time));
|
|
}
|
|
|
|
private IEnumerator DoShake(float strength, float time)
|
|
{
|
|
float elapsed = 0f;
|
|
|
|
while (elapsed < time)
|
|
{
|
|
elapsed += Time.deltaTime;
|
|
float x = Random.Range(-1f, 1f) * strength;
|
|
float y = Random.Range(-1f, 1f) * strength;
|
|
|
|
offsetter.m_Offset = new Vector3(x, y, originalOffset.z);
|
|
yield return null; // Wait for the next frame
|
|
}
|
|
|
|
// Reset the offset to the original position
|
|
offsetter.m_Offset = originalOffset;
|
|
}
|
|
}
|