forked from nhathuy7996/ReUseScript_Unity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CameraShake.cs
69 lines (58 loc) · 1.56 KB
/
CameraShake.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using UnityEngine;
using System.Collections;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;
public class CameraShake : MonoBehaviour
{
// Transform of the camera to shake. Grabs the gameObject's transform
// if null.
Transform camTransform;
// How long the object should shake for.
float _shakeDuration = 0f;
public float shakeDuration => _shakeDuration;
[SerializeField]
List<Color> BG_Color = new List<Color>();
[SerializeField]
// Amplitude of the shake. A larger value shakes the camera harder.
float shakeAmount = 0.7f, decreaseFactor = 1.0f;
public UnityEvent ShakeDone = null;
Vector3 originalPos;
void Awake()
{
if (camTransform == null)
{
camTransform = GetComponent(typeof(Transform)) as Transform;
}
}
void OnEnable()
{
originalPos = camTransform.localPosition;
}
void Update()
{
if (_shakeDuration > 0)
{
camTransform.localPosition = originalPos + Random.insideUnitSphere * shakeAmount;
_shakeDuration -= Time.deltaTime * decreaseFactor;
Camera.main.backgroundColor = BG_Color[1];
}
else
{
_shakeDuration = 0f;
camTransform.localPosition = originalPos;
Camera.main.backgroundColor = BG_Color[0];
}
}
public void Shake(float timeDur){
_shakeDuration = timeDur;
StartCoroutine(CallEventDone());
}
IEnumerator CallEventDone(){
yield return new WaitForSeconds(_shakeDuration);
if(ShakeDone != null){
ShakeDone.Invoke();
ShakeDone.RemoveAllListeners();
}
}
}