Newer
Older
lostmynuts / shared / js / Engine / Utils / MultiTween.js
class MultiTween
{
	get tweenValue() { return this.currentTween.tweenValue; }
	get MaxTime() { return this.currentTween.MaxTime; }
	set MaxTime(value) { this.currentTween.MaxTime = value; }
	pause()
	{
		this.currentTween.pause();
	}
	resume()
	{
		this.currentTween.resume();
	}
	get isPaused() { return this.currentTween.isPaused; }
	constructor(finish, update)
	{
		if (finish === undefined) finish = null;
		if (update === undefined) update = null;
		
		this.active = false;
		this.onFinish = finish;
		this.onUpdate = update;
		
		this.currentTween = new SimpleTween();
		this.currentTween.onFinish = this.internalOnFinish;
		
		this.tweens = [];
		this.currentTweenIndex = 0;
		this.loop = false;
	}
	
	addSimpleTween(tweenFunc, start, end, time, toInt /* = false*/)
	{
		if (toInt === undefined) toInt = false;
		this.addSimpleTweenAt(this.tweens.length, tweenFunc, start, end, time, toInt);
	}

	addSimpleTweenAt(index, tweenFunc, start, end, time, toInt /* = false*/)
	{
		if (toInt === undefined) toInt = false;
		
		this.tweens.splice(index, 0, { tweenFunc: tweenFunc, start: start, end: end, time: time, toInt: toInt });
		if (this.active && index <= this.currentTweenIndex)
		{
			this.currentTweenIndex++;
		}
	}

	clear()
	{
		this.stop();
		this.tweens.length = 0;
	}

	start(tweenIndex /* = 0*/)
	{
		if (tweenIndex === undefined) tweenIndex = 0;
		this.active = true;
		if (this.tweens.length == 0)
		{
			this.active = false;
			if (this.onFinish != null) this.onFinish();
		}
		else
		{
			this.setupTween(tweenIndex);
		}
	}

	setupTween(tweenIndex)
	{
		this.currentTweenIndex = tweenIndex % this.tweens.length;
		var info = this.tweens[currentTweenIndex];
		this.currentTween.init(this.internalOnUpdate, info.tweenFunc, info.start, info.end, info.time, info.toInt);
	}

	internalOnUpdate(val)
	{
		if (this.onUpdate != null) this.onUpdate(val);
	}

	internalOnFinish()
	{
		if (this.currentTweenIndex + 1 >= this.tweens.length)
		{
			if (!this.loop)
			{
				this.active = false;
				if (this.onFinish != null) this.onFinish();
				return;
			}
		}

		this.setupTween(this.currentTweenIndex + 1);
	}

	stop()
	{
		if (this.active)
		{
			this.currentTween.stop();
			this.currentTween.onFinish = this.internalOnFinish;

			this.active = false;
			this.onFinish = null;
			this.onUpdate = null;
		}
	}

	forceUpdateCall()
	{
		if (this.active && this.currentTween != null)
		{
			this.currentTween.forceUpdateCall();
		}
	}
}