wangguan
2020-11-04 2ae9edd5bfd8b8baabb8cd995485f9ade4faebc9
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class CameraShakeSimpleScript : MonoBehaviour {
 
    private Animation anim;
 
    void Start () {
        anim = GetComponent<Animation> ();
    }
 
    public void ShakeCamera() {    
        anim.Play(anim.clip.name);
    }
 
    //other shake option
    public void ShakeCaller (float amount, float duration){
        StartCoroutine (Shake(amount, duration));
    }
 
    IEnumerator Shake (float amount, float duration){
        Vector3 originalPos = transform.localPosition;
        int counter = 0;
 
        while (duration > 0.01f) {
            counter++;
 
            var x = Random.Range (-1f, 1f) * (amount/counter);
            var y = Random.Range (-1f, 1f) * (amount/counter);
 
            transform.localPosition = new Vector3 (x, y, originalPos.z);
 
            duration -= Time.deltaTime;
            
            yield return new WaitForSeconds (0.1f);
        }
 
        transform.localPosition = originalPos;
    }
}