Skip to content

Instantly share code, notes, and snippets.

@andresaraujo
Created May 25, 2015 02:15
Show Gist options
  • Save andresaraujo/9ab2af9ef21b5e79e626 to your computer and use it in GitHub Desktop.
Save andresaraujo/9ab2af9ef21b5e79e626 to your computer and use it in GitHub Desktop.
sprite animation api mock
import 'dart:math' as math;
void main() {
var sc = new AnimationCmp();
sc.add('idle', [1,2,3,4], 8);
sc.add('walk', [5,6,7,8], 12, loop: false);
sc.play('walk');
print(sc);
var sys = new AnimationSys();
//simulate a game loop
for(int i = 0; i < 80; i++) {
sys.update(sc, 1/60);
print(sc.frame);
}
}
class AnimationSys {
update(AnimationCmp sc, num dt) {
if (sc.animation == null) return;
sc.timer = sc.timer - dt;
if (sc.timer <= 0) {
sc.animationIndex = sc.animationIndex + 1;
if (sc.animationIndex > sc.animation['frames'].length -1) {
if (sc.animation['loop']) {
sc.animationIndex = 0;
} else {
sc.animation = null;
return;
}
}
sc.timer = sc.timer + sc.animation['fps'];
sc.frame = sc.animation['frames'][sc.animationIndex];
}
}
}
class AnimationCmp {
Map<String, Map> animations = {};
Map animation = {};
num timer;
int animationIndex = 0;
int frame;
add(String name, List<int> frames, num fps, {bool loop : true}) {
animations[name] = {
'frames' : frames,
'fps': fps != 0 ? 1 / fps.abs() : 1,
'loop': loop
};
}
play(String name, {bool reset : true}) {
var last = animation;
animation = animations[name];
if(reset || (animation != null && animation != last)) {
timer = animation['fps'];
animationIndex = 0;
frame = animation['frames'].first;
}
}
toString() => "$timer, $animationIndex, $frame, $animation, $animations";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment