-
Notifications
You must be signed in to change notification settings - Fork 450
/
Copy pathCameraShake.cs
66 lines (54 loc) · 2.07 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
using UnityEngine;
using System.Collections;
/*
* Usage: attach this script to a camera or any other object, call Shake() method to start shaking it
* To turn off, change influence to zero
* Attach the camera to an empty game object to keep its local position and rotation
*/
namespace UnityLibrary
{
public class CameraShake : MonoBehaviour
{
[Range(0f, 1f)]
public float shakeInfluence = 0.5f;
[Range(0f, 10f)]
public float rotationInfluence = 0f;
private Vector3 OriginalPos;
private Quaternion OriginalRot;
private bool isShakeRunning = false;
/// <summary>
/// Will shake the camera with a random value between minIntensity and maxIntensity for duration
/// </summary>
/// <param name="minIntensity"></param>
/// <param name="maxIntensity"></param>
/// <param name="duration"></param>
public void Shake(float minIntensity, float maxIntensity, float duration)
{
if (isShakeRunning)
return;
OriginalPos = transform.position;
OriginalRot = transform.rotation;
float shake = Random.Range(minIntensity, maxIntensity) * shakeInfluence;
duration *= shakeInfluence;
StartCoroutine(ProcessShake(shake, duration));
}
IEnumerator ProcessShake(float shake, float duration)
{
isShakeRunning = true;
float countdown = duration;
float initialShake = shake;
while (countdown > 0)
{
countdown -= Time.deltaTime;
float lerpIntensity = countdown / duration;
shake = Mathf.Lerp(0f, initialShake, lerpIntensity);
transform.position = OriginalPos + Random.insideUnitSphere * shake;
transform.rotation = Quaternion.Euler(OriginalRot.eulerAngles + Random.insideUnitSphere * shake * rotationInfluence);
yield return null;
}
transform.position = OriginalPos;
transform.rotation = OriginalRot;
isShakeRunning = false;
}
}
}