From 6e0b192671ce5e8574d85bb1778a8b32d0f75287 Mon Sep 17 00:00:00 2001 From: cha0s Date: Tue, 19 Mar 2019 20:58:19 -0500 Subject: [PATCH] refactor: animation swapping helpers --- packages/entity/traits/animated.js | 40 ++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/packages/entity/traits/animated.js b/packages/entity/traits/animated.js index d4a00e9..bfda305 100644 --- a/packages/entity/traits/animated.js +++ b/packages/entity/traits/animated.js @@ -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.