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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
 
namespace MoreMountains.NiceVibrations
{
    /// <summary>
    /// Add this bar to an object and link it to a bar (possibly the same object the script is on), and you'll be able to resize the bar object based on a current value, located between a min and max value.
    /// See the HealthBar.cs script for a use case
    /// </summary>
    public class MMProgressBar : MonoBehaviour
    {
        /// the possible fill modes 
        public enum FillModes { LocalScale, FillAmount, Width, Height }
        /// the possible directions for the fill (for local scale and fill amount only)
        public enum BarDirections { LeftToRight, RightToLeft, UpToDown, DownToUp }
        /// the possible timescales the bar can work on
        public enum TimeScales { UnscaledTime, Time }
 
        [Header("General Settings")]
        /// the local scale or fillamount value to reach when the bar is empty 
        public float StartValue = 0f;
        /// the local scale or fillamount value to reach when the bar is full
        public float EndValue = 1f;
        /// the direction this bar moves to
        public BarDirections BarDirection = BarDirections.LeftToRight;
        /// the foreground bar's fill mode
        public FillModes FillMode = FillModes.LocalScale;
        /// defines whether the bar will work on scaled or unscaled time (whether or not it'll keep moving if time is slowed down for example)
        public TimeScales TimeScale = TimeScales.UnscaledTime;
 
        [Header("Foreground Bar Settings")]
        /// whether or not the foreground bar should lerp
        public bool LerpForegroundBar = true;
        /// the speed at which to lerp the foreground bar
        public float LerpForegroundBarSpeed = 15f;
 
        [Header("Delayed Bar Settings")]
        /// the delay before the delayed bar moves (in seconds)
        public float Delay = 1f;
        /// whether or not the delayed bar's animation should lerp
        public bool LerpDelayedBar = true;
        /// the speed at which to lerp the delayed bar
        public float LerpDelayedBarSpeed = 15f;
 
        [Header("Bindings")]
        /// optional - the ID of the player associated to this bar
        public string PlayerID;
        /// the delayed bar
        public Transform DelayedBar;
        /// the main, foreground bar
        public Transform ForegroundBar;
 
        [Header("Bump")]
        /// whether or not the bar should "bump" when changing value
        public bool BumpScaleOnChange = true;
        /// whether or not the bar should bump when its value increases
        public bool BumpOnIncrease = false;
        /// the duration of the bump animation
        public float BumpDuration = 0.2f;
        /// whether or not the bar should flash when bumping
        public bool ChangeColorWhenBumping = true;
        /// the color to apply to the bar when bumping
        public Color BumpColor = Color.white;
        /// the curve to map the bump animation on
        public AnimationCurve BumpAnimationCurve = new AnimationCurve(new Keyframe(1, 1), new Keyframe(0.3f, 1.05f), new Keyframe(1, 1));
        /// the curve to map the bump animation color animation on
        public AnimationCurve BumpColorAnimationCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(0.3f, 1f), new Keyframe(1, 0));
        /// whether or not the bar is bumping right now
        public bool Bumping { get; protected set; }
 
        [Header("Realtime")]
        /// whether or not this progress bar should update itself every update (if not, you'll have to update it using the UpdateBar method
        public bool AutoUpdating = false;
        /// the current progress of the bar
        [Range(0f, 1f)]
        public float BarProgress;
        
        protected float _targetFill;
        protected Vector3 _targetLocalScale = Vector3.one;
        protected float _newPercent;
        protected float _lastPercent;
        protected float _lastUpdateTimestamp;
        protected bool _bump = false;
        protected Color _initialColor;
        protected Vector3 _initialScale;
        protected Vector3 _newScale;
        protected Image _foregroundImage;
        protected Image _delayedImage;
        protected bool _initialized;
        protected Vector2 _initialFrontBarSize;
 
        /// <summary>
        /// On start we store our image component
        /// </summary>
        protected virtual void Start()
        {
            _initialScale = this.transform.localScale;
 
            if (ForegroundBar != null)
            {
                _foregroundImage = ForegroundBar.GetComponent<Image>();
                _initialFrontBarSize = _foregroundImage.rectTransform.sizeDelta;
            }
            if (DelayedBar != null)
            {
                _delayedImage = DelayedBar.GetComponent<Image>();
            }
            _initialized = true;
        }
 
        /// <summary>
        /// On Update we update our bars
        /// </summary>
        protected virtual void Update()
        {
            AutoUpdate();
            UpdateFrontBar();
            UpdateDelayedBar();
        }
 
        protected virtual void AutoUpdate()
        {
            if (!AutoUpdating)
            {
                return;
            }
 
            _newPercent = Remap(BarProgress, 0f, 1f, StartValue, EndValue);
            _targetFill = _newPercent;
            _lastUpdateTimestamp = (TimeScale == TimeScales.Time) ? Time.time : Time.unscaledTime;
        }
 
        /// <summary>
        /// Updates the front bar's scale
        /// </summary>
        protected virtual void UpdateFrontBar()
        {
            float currentDeltaTime = (TimeScale == TimeScales.Time) ? Time.deltaTime : Time.unscaledTime;
 
            if (ForegroundBar != null)
            {
                switch (FillMode)
                {
                    case FillModes.LocalScale:
                        _targetLocalScale = Vector3.one;
                        switch (BarDirection)
                        {
                            case BarDirections.LeftToRight:
                                _targetLocalScale.x = _targetFill;
                                break;
                            case BarDirections.RightToLeft:
                                _targetLocalScale.x = 1f - _targetFill;
                                break;
                            case BarDirections.DownToUp:
                                _targetLocalScale.y = _targetFill;
                                break;
                            case BarDirections.UpToDown:
                                _targetLocalScale.y = 1f - _targetFill;
                                break;
                        }
 
                        if (LerpForegroundBar)
                        {
                            _newScale = Vector3.Lerp(ForegroundBar.localScale, _targetLocalScale, currentDeltaTime * LerpForegroundBarSpeed);
                        }
                        else
                        {
                            _newScale = _targetLocalScale;
                        }
 
                        ForegroundBar.localScale = _newScale;
                        break;
 
                    case FillModes.Width:
                        if (_foregroundImage == null)
                        {
                            return;
                        }
                        float newSizeX = Remap(_targetFill, 0f, 1f, 0, _initialFrontBarSize.x);
                        newSizeX = Mathf.Lerp(_foregroundImage.rectTransform.sizeDelta.x, newSizeX, currentDeltaTime * LerpForegroundBarSpeed);
                        _foregroundImage.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, newSizeX);
                        break;
 
                    case FillModes.Height:
                        if (_foregroundImage == null)
                        {
                            return;
                        }
                        float newSizeY = Remap(_targetFill, 0f, 1f, 0, _initialFrontBarSize.y);
                        newSizeY = Mathf.Lerp(_foregroundImage.rectTransform.sizeDelta.x, newSizeY, currentDeltaTime * LerpForegroundBarSpeed);
                        _foregroundImage.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, newSizeY);
                        break;
 
                    case FillModes.FillAmount:
                        if (_foregroundImage == null)
                        {
                            return;
                        }
                        if (LerpForegroundBar)
                        {
                            _foregroundImage.fillAmount = Mathf.Lerp(_foregroundImage.fillAmount, _targetFill, currentDeltaTime * LerpForegroundBarSpeed);
                        }
                        else
                        {
                            _foregroundImage.fillAmount = _targetFill;
                        }
                        break;
                }
            }
        }
 
        /// <summary>
        /// Updates the delayed bar's scale
        /// </summary>
        protected virtual void UpdateDelayedBar()
        {
            float currentDeltaTime = (TimeScale == TimeScales.Time) ? Time.deltaTime : Time.unscaledDeltaTime;
            float currentTime = (TimeScale == TimeScales.Time) ? Time.time : Time.unscaledTime;
 
            if (DelayedBar != null)
            {
                if (currentTime - _lastUpdateTimestamp > Delay)
                {
                    if (FillMode == FillModes.LocalScale)
                    {
                        _targetLocalScale = Vector3.one;
 
                        switch (BarDirection)
                        {
                            case BarDirections.LeftToRight:
                                _targetLocalScale.x = _targetFill;
                                break;
                            case BarDirections.RightToLeft:
                                _targetLocalScale.x = 1f - _targetFill;
                                break;
                            case BarDirections.DownToUp:
                                _targetLocalScale.y = _targetFill;
                                break;
                            case BarDirections.UpToDown:
                                _targetLocalScale.y = 1f - _targetFill;
                                break;
                        }
 
                        if (LerpDelayedBar)
                        {
                            _newScale = Vector3.Lerp(DelayedBar.localScale, _targetLocalScale, currentDeltaTime * LerpDelayedBarSpeed);
                        }
                        else
                        {
                            _newScale = _targetLocalScale;
                        }
                        DelayedBar.localScale = _newScale;
                    }
 
                    if ((FillMode == FillModes.FillAmount) && (_delayedImage != null))
                    {
                        if (LerpDelayedBar)
                        {
                            _delayedImage.fillAmount = Mathf.Lerp(_delayedImage.fillAmount, _targetFill, currentDeltaTime * LerpDelayedBarSpeed);
                        }
                        else
                        {
                            _delayedImage.fillAmount = _targetFill;
                        }
                    }
                }
            }
        }
 
        /// <summary>
        /// Updates the bar's values based on the specified parameters
        /// </summary>
        /// <param name="currentValue">Current value.</param>
        /// <param name="minValue">Minimum value.</param>
        /// <param name="maxValue">Max value.</param>
        public virtual void UpdateBar(float currentValue, float minValue, float maxValue)
        {
            _newPercent = Remap(currentValue, minValue, maxValue, StartValue, EndValue);
            if ((_newPercent != BarProgress) && !Bumping)
            {
                Bump();
            }
            BarProgress = _newPercent;
            _targetFill = _newPercent;
            _lastUpdateTimestamp = (TimeScale == TimeScales.Time) ? Time.time : Time.unscaledTime;
            _lastPercent = _newPercent;
        }
 
        /// <summary>
        /// Triggers a camera bump
        /// </summary>
        public virtual void Bump()
        {
            if (!BumpScaleOnChange || !_initialized)
            {
                return;
            }
            if (!BumpOnIncrease && (_lastPercent < _newPercent))
            {
                return;
            }
            if (this.gameObject.activeInHierarchy)
            {
                StartCoroutine(BumpCoroutine());
            }
        }
 
        /// <summary>
        /// A coroutine that (usually quickly) changes the scale of the bar 
        /// </summary>
        /// <returns>The coroutine.</returns>
        protected virtual IEnumerator BumpCoroutine()
        {
            float journey = 0f;
            float currentDeltaTime = (TimeScale == TimeScales.Time) ? Time.deltaTime : Time.unscaledDeltaTime;
 
            Bumping = true;
            if (_foregroundImage != null)
            {
                _initialColor = _foregroundImage.color;
            }
 
            while (journey <= BumpDuration)
            {
                journey = journey + currentDeltaTime;
                float percent = Mathf.Clamp01(journey / BumpDuration);
                float curvePercent = BumpAnimationCurve.Evaluate(percent);
                float colorCurvePercent = BumpColorAnimationCurve.Evaluate(percent);
                this.transform.localScale = curvePercent * _initialScale;
 
                if (ChangeColorWhenBumping && (_foregroundImage != null))
                {
                    _foregroundImage.color = Color.Lerp(_initialColor, BumpColor, colorCurvePercent);
                }
 
                yield return null;
            }
            _foregroundImage.color = _initialColor;
            Bumping = false;
            yield return null;
 
        }
 
 
        protected virtual float Remap(float x, float A, float B, float C, float D)
        {
            float remappedValue = C + (x - A) / (B - A) * (D - C);
            return remappedValue;
        }
    }
}