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.
HighGroundRoyaleNetcode/Assets/Scripts/Gameplay/GameplayObjects/Character/CinemachineShake.cs

57 lines
1.6 KiB
C#

using UnityEngine;
using System.Collections;
using Cinemachine;
public class CinemachineShake : MonoBehaviour
{
public static CinemachineShake Instance { get; private set; }
private CinemachineFreeLook freeLookCamera;
private Coroutine shakeCoroutine;
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
Destroy(gameObject);
}
freeLookCamera = GetComponent<CinemachineFreeLook>();
if (freeLookCamera == null)
{
Debug.LogError("[FreeLookCameraShake] No Cinemachine FreeLook Camera found!");
}
}
public void Shake(float duration = 0.3f, float magnitude = 0.2f)
{
if (shakeCoroutine != null)
{
StopCoroutine(shakeCoroutine);
}
shakeCoroutine = StartCoroutine(ShakeRoutine(duration, magnitude));
}
private IEnumerator ShakeRoutine(float duration, float magnitude)
{
float elapsed = 0f;
float originalX = freeLookCamera.m_XAxis.Value;
float originalY = freeLookCamera.m_YAxis.Value;
while (elapsed < duration)
{
freeLookCamera.m_XAxis.Value = originalX + Random.Range(-magnitude, magnitude);
freeLookCamera.m_YAxis.Value = originalY + Random.Range(-magnitude, magnitude);
elapsed += Time.deltaTime;
yield return null;
}
freeLookCamera.m_XAxis.Value = originalX; // Reset horizontal shake
freeLookCamera.m_YAxis.Value = originalY; // Reset vertical shake
}
}