Newer
Older
lostmynuts / shared / js / Engine / Display / AnimationController.js
class AnimationController
{
	constructor()
	{
		this.x = 0;
		this.y = 0;
		this.scaleX = 1;
		this.scaleY = 1;
		this.rotation = 0;
		this.cleanup = false;
		this.drawable = null;
		this.animations = [];
	}

	setDrawable(drawable /*Drawable*/)
	{
		if(this.drawable != null && drawable == null)
		{
			this.drawable.x = this.x;
			this.drawable.y = this.y;
			this.drawable.scale.x = this.scaleX;
			this.drawable.scale.y = this.scaleY;
			this.drawable.rotation = this.rotation;
		}
		this.drawable = drawable;
		
		if (drawable != null)
		{
			this.x = drawable.x;
			this.y = drawable.y;
			this.scaleX = drawable.scale.x;
			this.scaleY = drawable.scale.y;
			this.rotation = drawable.rotation;
			
			Engine.EnterFrameManagerInstance.add(this, (dt) => this.update(dt));
		}
		else
		{
			Engine.EnterFrameManagerInstance.remove(this);
		}
	}

	update(timeElapsed /*float*/)
	{
		if (this.drawable == null) return;
		var tRotation = this.rotation;
		
		var tx = X;
		var ty = Y;
		
		var newScaleX = this.scaleX;
		var newScaleY = this.scaleY;
		
		for (var i = 0; i < this.animations.length; i++)
		{
			var animation = this.animations[i];
			if (animation.active)
			{
				animation.update(timeElapsed);
				
				tx += animation.x;
				ty += animation.y;
				newScaleX *= animation.scale.x;
				newScaleY *= animation.scale.y;
				tRotation += animation.rotation;
			}
		}
		
		this.cleanUpAnimations();
		
		if (drawable != null)
		{
			this.drawable.x = tx;
			this.drawable.y = ty;
			this.drawable.scale.x = newScaleX;
			this.drawable.scale.y = newScaleY;
			this.drawable.rotation = tRotation;
		}
	}

	removeAllAnimations()
	{
		this.setDrawable(null);
		this.animations.length = 0;
	}

	cleanUpAnimations()
	{
		for (var i = this.animations.length - 1; i >= 0; i--)
		{
			if (!this.animations[i].active)
			{
				this.animations.remove(this.animations[i]);
			}
		}
	}

	addAnimation(animation /*Animation*/)
	{
		this.animations.push(animation);
	}

	removeAnimation(animation /*Animation*/)
	{
		this.animations.remove(animation);
	}
}