comparison src/animatedsprite.d @ 4:292df259cc85

view + sprite consumers, animated sprite working
author fred@reichbier.de
date Fri, 18 Jul 2008 16:12:41 +0200
parents
children
comparison
equal deleted inserted replaced
3:a9af6ec19195 4:292df259cc85
1 module animatedsprite;
2
3 import dsfml.window.all;
4 import dsfml.system.all;
5 import dsfml.graphics.all;
6
7 class Frame {
8 Image image;
9 int length; // length in frames
10
11 this(Image image, int length) {
12 this.image = image;
13 this.length = length;
14 }
15 }
16
17 class Animation {
18 private Frame[] frames;
19 private int current_frame_idx;
20 private Frame current_frame;
21 private int frame_counter;
22
23 this() {
24
25 }
26
27 void add_frame(Image image, int length) {
28 this.frames ~= new Frame(image, length);
29 }
30
31 void play() {
32 this.current_frame = this.frames[0];
33 this.current_frame_idx = 0;
34 }
35
36 Image get_image() {
37 if(this.frame_counter >= this.current_frame.length) {
38 this.frame_counter = 0;
39 this.current_frame_idx++;
40 if (this.frames.length <= this.current_frame_idx) {
41 // animation stop
42 return null;
43 }
44 this.current_frame = this.frames[this.current_frame_idx];
45 }
46 this.frame_counter++;
47 return this.current_frame.image;
48 }
49 }
50
51 class AnimatedSprite : Sprite {
52 private Animation current_animation = null;
53 private bool is_loop = false;
54
55 /* play an animation now. */
56 void play_animation(Animation animation, bool loop=false) {
57 this.current_animation = animation;
58 this.is_loop = loop;
59 this.current_animation.play();
60 }
61
62 /* update everything. Perfect for an animated sprite */
63 void update() {
64 if(this.current_animation) {
65 Image img = this.current_animation.get_image();
66 if(img) {
67 this.setImage(img);
68 }
69 else if (this.is_loop) {
70 this.current_animation.play(); // is a loop, play again
71 } else {
72 this.current_animation = null;
73 }
74 }
75 }
76 }