AkiraPixelWind/Assets/Scripts/Main/Camera/CameraShake.cs

61 lines
1.5 KiB
C#

using Axibug;
using Axibug.Event;
using Game;
using System.Collections;
using UnityEngine;
//TODO ºóÐøÒƶ¯µ½ºÏÊʵÄλÖÃ
public class CameraShake : MonoBehaviour
{
public float _magnitude = 0.02f;
private void OnEnable()
{
AppEntry.Event.Subscribe(CameraShakeEventArgs.EventId, OnCameraShakeEventArgs);
}
private void OnDisable()
{
AppEntry.Event.Unsubscribe(CameraShakeEventArgs.EventId, OnCameraShakeEventArgs);
}
private void OnCameraShakeEventArgs(object sender, LogicEventArgs e)
{
CameraShakeEventArgs msg = (CameraShakeEventArgs)e;
if (msg == null) throw new GameException("OnCameraShakeEventArgs is null");
StartShake();
}
void StartShake()
{
if (IEnumerator_Shake != null)
StopCoroutine(IEnumerator_Shake);
IEnumerator_Shake = StartCoroutine(PlayCameraShakeAnimation(0.1f, _magnitude));
}
Coroutine IEnumerator_Shake;
public IEnumerator PlayCameraShakeAnimation(float duration, float magnitude)
{
Vector3 originalPosition = Vector3.zero;
float elapsedTime = 0f;
while (elapsedTime < duration)
{
float x = Random.Range(-1f, 1f) * magnitude;
float y = Random.Range(-1f, 1f) * magnitude;
transform.localPosition = new Vector3(x, y, originalPosition.z);
elapsedTime += Time.deltaTime;
yield return null;
}
transform.localPosition = originalPosition;
IEnumerator_Shake = null;
}
}