-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpriteAnimation.cs
65 lines (54 loc) · 2 KB
/
SpriteAnimation.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
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Drawing;
using Color = Microsoft.Xna.Framework.Color;
using Rectangle = Microsoft.Xna.Framework.Rectangle;
namespace EndlessFight
{
public class SpriteManager
{
protected Texture2D Texture;
public Vector2 Position = Vector2.Zero;
public Color Color = Color.White;
public Vector2 Origin;
public float Rotation = 0f;
public float Scale = 1f;
public SpriteEffects SpriteEffect;
public Size Size;
public int FrameWidth;
protected Rectangle[] Rectangles;
public int FrameIndex = 0;
public SpriteManager(Texture2D texture, int frames)
{
Texture = texture;
Rectangles = new Rectangle[frames];
var frameWidth = Texture.Width / frames;
Size = new(frameWidth, Texture.Height);
for (var i = 0; i < frames; i++)
Rectangles[i] = new Rectangle(i * frameWidth, 0, frameWidth, Texture.Height);
}
public void Draw(SpriteBatch spriteBatch) =>
spriteBatch.Draw(Texture, Position, Rectangles[FrameIndex],
Color, Rotation, Origin, Scale, SpriteEffect, 0f);
}
public class SpriteAnimation : SpriteManager
{
private float timeElapsed;
public bool IsLooping = true;
public int FramesPerSecond { set { timeToUpdate = 1f / value; } }
private float timeToUpdate;
public SpriteAnimation(Texture2D Texture, int frames, int fps) : base(Texture, frames)
=> FramesPerSecond = fps;
public void Update()
{
timeElapsed += Globals.ElapsedSeconds;
if (timeElapsed > timeToUpdate)
{
timeElapsed -= timeToUpdate;
if (FrameIndex < Rectangles.Length - 1) FrameIndex++;
else if (IsLooping) FrameIndex = 0;
}
}
public void SetFrame(int frame) => FrameIndex = frame;
}
}