refactor: animation swapping helpers

This commit is contained in:
cha0s 2019-03-19 20:58:19 -05:00
parent 3b0efe4e9b
commit 6e0b192671

View File

@ -1,6 +1,6 @@
import {compose} from '@avocado/core';
import {hasGraphics, AnimationView} from '@avocado/graphics';
import {Vector} from '@avocado/math';
import {Rectangle, Vector} from '@avocado/math';
import {Animation} from '@avocado/timing';
import {simpleState, Trait} from '../trait';
@ -29,6 +29,17 @@ class AnimatedBase extends Trait {
};
}
hideAnimation(key) {
if (!this.animationViews) {
return;
}
const animationView = this.animationViews[key];
if (!animationView) {
return;
}
this.entity.container.removeChild(animationView);
}
initialize() {
this.animations = {};
this.animationViews = undefined;
@ -84,12 +95,27 @@ class AnimatedBase extends Trait {
// Ensure animation is made visible upfront.
const isCurrentAnimation = key === this.entity.currentAnimation;
if (isCurrentAnimation) {
this.entity.container.addChild(this.animationViews[key]);
this.showAnimation(key);
}
});
});
}
showAnimation(key) {
if (!this.animationViews) {
return;
}
const animationView = this.animationViews[key];
if (!animationView) {
return;
}
const {animation} = animationView;
const size = Rectangle.size(animation.sourceRectangle)
const offset = Vector.scale(size, -0.5);
animationView.position = offset;
this.entity.container.addChild(animationView);
}
listeners() {
return {
currentAnimationChanged: (oldKey) => {
@ -103,14 +129,8 @@ class AnimatedBase extends Trait {
return;
}
// Swap the animation.
const oldAnimationView = this.animationViews[oldKey];
if (oldAnimationView) {
this.entity.container.removeChild(oldAnimationView);
}
const animationView = this.animationViews[this.entity.currentAnimation];
if (animationView) {
this.entity.container.addChild(animationView);
}
this.hideAnimation(oldKey);
this.showAnimation(this.entity.currentAnimation);
},
currentFrameChanged: () => {
// Animation index from current entity frame.