wangguan
2020-12-29 452c75675679c44cc39b04bdb7d330d7c5c14d5c
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
 
namespace MoreMountains.NiceVibrations
{
    public class MMUIShaker : MonoBehaviour
    {
        public float Intensity;
        public float Sharpness;
        public bool Shaking = false;
 
        protected Vector3 _initialPosition;
        protected Vector3 _shakePosition;
        protected RectTransform _rectTransform;
 
        protected virtual void Start()
        {            
            _rectTransform = this.gameObject.GetComponent<RectTransform>();
            _initialPosition = _rectTransform.localPosition;
        }
 
        public virtual IEnumerator Shake(float duration)
        {
            Shaking = true;
            yield return new WaitForSeconds(duration);
            Shaking = false;
        }
 
        protected virtual void Update()
        {
            if (!Shaking)
            {
                _rectTransform.localPosition = _initialPosition;
                return;
            }
            else
            {
                _shakePosition.x = Mathf.PerlinNoise(-(Time.time) * Sharpness, Time.time * Sharpness) * Intensity - Intensity / 2f;
                _shakePosition.y = Mathf.PerlinNoise(-(Time.time + 0.25f) * Sharpness, Time.time * Sharpness) * Intensity - Intensity / 2f;
                _shakePosition.z = Mathf.PerlinNoise(-(Time.time + 0.5f) * Sharpness, Time.time * Sharpness) * Intensity - Intensity / 2f;
                _rectTransform.localPosition = _initialPosition + _shakePosition;
            }
        }
    }
}