forked from UnityCommunity/UnityLibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCameraShake.cs
More file actions
56 lines (47 loc) · 1.91 KB
/
Copy pathCameraShake.cs
File metadata and controls
56 lines (47 loc) · 1.91 KB
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
using UnityEngine;
using System.Collections;
// usage: attach this script into camera, call Shake() method to start
// source: http://answers.unity3d.com/answers/992509/view.html
public class CameraShake : MonoBehaviour
{
public bool shakePosition;
public bool shakeRotation;
public float shakeIntensityMin = 0.1f;
public float shakeIntensityMax = 0.5f;
public float shakeDecay = 0.02f;
private Vector3 OriginalPos;
private Quaternion OriginalRot;
private bool isShakeRunning = false;
// call this function to start shaking
public void Shake()
{
OriginalPos = transform.position;
OriginalRot = transform.rotation;
StartCoroutine("ProcessShake");
}
IEnumerator ProcessShake()
{
if (!isShakeRunning)
{
isShakeRunning = true;
float currentShakeIntensity = Random.Range(shakeIntensityMin, shakeIntensityMax);
while (currentShakeIntensity > 0)
{
if (shakePosition)
{
transform.position = OriginalPos + Random.insideUnitSphere * currentShakeIntensity;
}
if (shakeRotation)
{
transform.rotation = new Quaternion(OriginalRot.x + Random.Range(-currentShakeIntensity, currentShakeIntensity) * .2f,
OriginalRot.y + Random.Range(-currentShakeIntensity, currentShakeIntensity) * .2f,
OriginalRot.z + Random.Range(-currentShakeIntensity, currentShakeIntensity) * .2f,
OriginalRot.w + Random.Range(-currentShakeIntensity, currentShakeIntensity) * .2f);
}
currentShakeIntensity -= shakeDecay;
yield return null;
}
isShakeRunning = false;
}
}
}