Mercurial > projects > myrrdin
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/animatedsprite.d Fri Jul 18 16:12:41 2008 +0200 @@ -0,0 +1,76 @@ +module animatedsprite; + +import dsfml.window.all; +import dsfml.system.all; +import dsfml.graphics.all; + +class Frame { + Image image; + int length; // length in frames + + this(Image image, int length) { + this.image = image; + this.length = length; + } +} + +class Animation { + private Frame[] frames; + private int current_frame_idx; + private Frame current_frame; + private int frame_counter; + + this() { + + } + + void add_frame(Image image, int length) { + this.frames ~= new Frame(image, length); + } + + void play() { + this.current_frame = this.frames[0]; + this.current_frame_idx = 0; + } + + Image get_image() { + if(this.frame_counter >= this.current_frame.length) { + this.frame_counter = 0; + this.current_frame_idx++; + if (this.frames.length <= this.current_frame_idx) { + // animation stop + return null; + } + this.current_frame = this.frames[this.current_frame_idx]; + } + this.frame_counter++; + return this.current_frame.image; + } +} + +class AnimatedSprite : Sprite { + private Animation current_animation = null; + private bool is_loop = false; + + /* play an animation now. */ + void play_animation(Animation animation, bool loop=false) { + this.current_animation = animation; + this.is_loop = loop; + this.current_animation.play(); + } + + /* update everything. Perfect for an animated sprite */ + void update() { + if(this.current_animation) { + Image img = this.current_animation.get_image(); + if(img) { + this.setImage(img); + } + else if (this.is_loop) { + this.current_animation.play(); // is a loop, play again + } else { + this.current_animation = null; + } + } + } +}