-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathAnimatedSprite.cs
98 lines (86 loc) · 2.97 KB
/
AnimatedSprite.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
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Desktoptale
{
public class AnimatedSprite : IAnimatedSprite
{
public bool Playing { get; private set; }
public bool Loop { get; set; }
public int LoopPoint { get; set; }
public double Framerate { get; set; }
public int FrameCount { get; private set; }
public int StartFrame
{
get => startFrame;
set
{
startFrame = value;
if (!Playing && CurrentFrameIndex == 0) CurrentFrameIndex = value;
}
}
public int CurrentFrameIndex { get; set; }
public Point FrameSize { get; }
private Texture2D spritesheet;
private bool justStarted;
private TimeSpan nextFrameUpdate;
private int startFrame;
public AnimatedSprite(Texture2D spritesheet, int frameCount)
{
this.spritesheet = spritesheet;
this.FrameCount = frameCount;
FrameSize = new Point(spritesheet.Width / frameCount, spritesheet.Height);
}
public void Play()
{
Playing = true;
justStarted = true;
}
public void Pause()
{
Playing = false;
}
public void Stop()
{
Playing = false;
CurrentFrameIndex = StartFrame;
}
public void Update(GameTime gameTime)
{
if (Playing && FrameCount > 1)
{
if (justStarted)
{
TimeSpan nextScheduledUpdate = Framerate == 0 ? TimeSpan.MaxValue : gameTime.TotalGameTime + TimeSpan.FromSeconds(1 / Framerate);
nextFrameUpdate = nextScheduledUpdate;
justStarted = false;
}
if (nextFrameUpdate < gameTime.TotalGameTime)
{
TimeSpan nextScheduledUpdate = Framerate == 0 ? TimeSpan.MaxValue : gameTime.TotalGameTime + TimeSpan.FromSeconds(1 / Framerate);
nextFrameUpdate = nextScheduledUpdate;
if (CurrentFrameIndex < FrameCount - 1)
{
CurrentFrameIndex++;
}
else
{
if (Loop) CurrentFrameIndex = LoopPoint;
}
}
}
}
public void Draw(SpriteBatch spriteBatch,
Vector2 position,
Color color,
float rotation,
Vector2 origin,
Vector2 scale,
SpriteEffects effects,
float layerDepth)
{
Rectangle sourceRectangle = new Rectangle(CurrentFrameIndex * FrameSize.X, 0, FrameSize.X, FrameSize.Y);
spriteBatch.Draw(spritesheet, position, sourceRectangle, color, rotation, origin, scale, effects, layerDepth);
}
}
}