1 /** 2 Allows storing instances of a looping, linear animation 3 */ 4 module dgt.animation; 5 6 import dgt.array, dgt.texture; 7 8 /** 9 A frame in an animation 10 */ 11 struct Frame 12 { 13 public: 14 /** 15 The actual thing to draw when this frame is active 16 */ 17 Texture image; 18 /** 19 The number of animation ticks this frame remains active 20 21 An animation tick occurs once a frame, to a default of 60 times a second 22 */ 23 int delay; 24 } 25 26 /** 27 An animated instance 28 29 It progresses linearly from frame to frame and loops when it finishes. 30 */ 31 struct Animation 32 { 33 private: 34 const(Frame[]) frames; 35 int currentFrame = 0, currentTime = 0; 36 37 @nogc nothrow public: 38 /** 39 Create an animation from an array of frames 40 */ 41 pure this(in Frame[] frames) 42 { 43 this.frames = frames; 44 } 45 46 47 /** 48 Tick the animation forward one frame 49 50 Returns: The current frame of the animation 51 */ 52 pure ref const(Texture) update() 53 { 54 currentTime++; 55 if (currentTime >= frames[currentFrame].delay) 56 { 57 currentTime = 0; 58 currentFrame = cast(int)((currentFrame + 1) % frames.length); 59 } 60 return frames[currentFrame].image; 61 } 62 63 /** 64 Returns: The current frame of the animation 65 */ 66 pure @property ref const(Texture) texture() const 67 { 68 return frames[currentFrame].image; 69 } 70 }