-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathAnimatedTexture.cs
106 lines (88 loc) · 3.08 KB
/
AnimatedTexture.cs
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
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
/// <summary>
/// A helper class for handling animated textures.
/// </summary>
public class AnimatedTexture
{
// Number of frames in the animation.
private int frameCount;
// The animation spritesheet.
private Texture2D myTexture;
// The number of frames to draw per second.
private float timePerFrame;
// The current frame being drawn.
private int frame;
// Total amount of time the animation has been running.
private float totalElapsed;
// Is the animation currently running?
private bool isPaused;
// The current rotation, scale and draw depth for the animation.
public float Rotation, Scale, Depth;
// The origin point of the animated texture.
public Vector2 Origin;
public AnimatedTexture(Vector2 origin, float rotation, float scale, float depth)
{
this.Origin = origin;
this.Rotation = rotation;
this.Scale = scale;
this.Depth = depth;
}
public void Load(ContentManager content, string asset, int frameCount, int framesPerSec)
{
this.frameCount = frameCount;
myTexture = content.Load<Texture2D>(asset);
timePerFrame = (float)1 / framesPerSec;
frame = 0;
totalElapsed = 0;
isPaused = false;
}
public void UpdateFrame(float elapsed)
{
if (isPaused)
return;
totalElapsed += elapsed;
if (totalElapsed > timePerFrame)
{
frame++;
// Keep the Frame between 0 and the total frames, minus one.
frame %= frameCount;
totalElapsed -= timePerFrame;
}
}
public void DrawFrame(SpriteBatch batch, Vector2 screenPos)
{
DrawFrame(batch, frame, screenPos);
}
public void DrawFrame(SpriteBatch batch, int frame, Vector2 screenPos)
{
int FrameWidth = myTexture.Width / frameCount;
Rectangle sourcerect = new Rectangle(FrameWidth * frame, 0,
FrameWidth, myTexture.Height);
batch.Draw(myTexture, screenPos, sourcerect, Color.White,
Rotation, Origin, Scale, SpriteEffects.None, Depth);
}
public bool IsPaused
{
get { return isPaused; }
}
public void Reset()
{
frame = 0;
totalElapsed = 0f;
}
public void Stop()
{
Pause();
Reset();
}
public void Play()
{
isPaused = false;
}
public void Pause()
{
isPaused = true;
}
}