-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpriteAnimation.cs
More file actions
87 lines (73 loc) · 2.11 KB
/
SpriteAnimation.cs
File metadata and controls
87 lines (73 loc) · 2.11 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
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
using UnityEngine;
using UnityEngine.Events;
namespace Agricosmic.Utilities
{
public class SpriteAnimation : MonoBehaviour
{
[SerializeField] private Sprite[] _frames = { };
[SerializeField] private float _timePerFrame = 0.2f;
[SerializeField] private bool _loop = true;
[SerializeField] private bool _autoplay = true;
[SerializeField] private SpriteRenderer _renderer;
public UnityEvent AnimationCycled;
private bool _playing = false;
private int _frameIndex = 0;
private float _frameTime = 0f;
private void Start()
{
if (_renderer == null) _renderer = GetComponent<SpriteRenderer>();
if (_autoplay) _playing = true;
}
private void Update()
{
if (_frames.Length == 0)
{
Debug.LogWarning("SpriteAnimation on " + name + " has no frames! Pausing...");
_playing = false;
}
if (_playing)
{
_frameTime += Time.deltaTime;
if (_frameTime >= _timePerFrame)
{
AdvanceFrame();
}
}
UpdateGraphics();
}
public void Play() => _playing = true;
public void Pause() => _playing = false;
public void Reset()
{
_frameTime = 0;
_frameIndex = 0;
}
public void Stop()
{
_playing = false;
Reset();
}
public void AdvanceFrame()
{
_frameTime = 0;
_frameIndex++;
if (_frameIndex >= _frames.Length)
{
if (_loop)
{
_frameIndex = 0;
}
else
{
_frameIndex = _frames.Length - 1;
_playing = false;
AnimationCycled?.Invoke();
}
}
}
private void UpdateGraphics()
{
_renderer.sprite = _frames[_frameIndex];
}
}
}