| 7 | using System.Threading.Tasks; |
| 8 | |
| 9 | class DemoAnim<T> |
| 10 | { |
| 11 | class TimeCompare : IComparer<(float time, T data)> |
| 12 | { public int Compare((float time, T data) a, (float time, T data) b) => a.time.CompareTo(b.time); } |
| 13 | |
| 14 | TimeCompare _comparer = new TimeCompare(); |
| 15 | (float time,T data)[] _frames; |
| 16 | Func<T,T,float,T> _lerp; |
| 17 | float _startTime; |
| 18 | float _updated; |
| 19 | float _speed = 1; |
| 20 | T _curr; |
| 21 | |
| 22 | public T Current { get { |
| 23 | float now = Time.Totalf; |
| 24 | if (now == _updated) |
| 25 | return _curr; |
| 26 | |
| 27 | float elapsed = (now - _startTime) * _speed; |
| 28 | _updated = now; |
| 29 | _curr = Sample(elapsed); |
| 30 | |
| 31 | return _curr; |
| 32 | } } |
| 33 | |
| 34 | public bool Playing => (Time.Totalf - _startTime) <= _frames[_frames.Length-1].time; |
| 35 | public float Duration => _frames[_frames.Length - 1].time; |
| 36 | |
| 37 | public DemoAnim(Func<T, T, float, T> lerp, params (float,T)[] frames) |
| 38 | { |
| 39 | _frames = frames; |
| 40 | _lerp = lerp; |
| 41 | _startTime = Time.Totalf; |
| 42 | } |
| 43 | |
| 44 | public void Play(float speed = 1) |
| 45 | { |
| 46 | _speed = speed; |
| 47 | _startTime = Time.Totalf; |
| 48 | } |
| 49 | |
| 50 | T Sample(float time) |
| 51 | { |
| 52 | if (time <= _frames[0].time) |
| 53 | return _frames[0].data; |
| 54 | if (time >= _frames[_frames.Length - 1].time) |
| 55 | return _frames[_frames.Length - 1].data; |
| 56 | |
| 57 | int item = Array.BinarySearch(_frames, (time,default(T)), _comparer); |
| 58 | if (item > 0) |
| 59 | return _frames[item].data; |
| 60 | else |
| 61 | { |
| 62 | item = ~item; |
| 63 | var p1 = _frames[item - 1]; |
| 64 | var p2 = _frames[item]; |
| 65 | float pct = (time - p1.time) / (p2.time - p1.time); |
| 66 | return _lerp(p1.data, p2.data, pct); |
nothing calls this directly
no outgoing calls
no test coverage detected