Chaining Animations

Hey,

has someone an elegant way of chaining animations togehter?
The animations are created using Texture Packer and it spits out multiple packs. The goal is to animate a lot of stuff, so I don’t want to create 35 nested callbacks or whatever. But I can’t find a proper/clean solution for that. I tried hoisting, context variations and simple arrays of objects.

I have tried using async await for tweens and animations. This is probably not its true intended use, but it served its purpose to flatten out such callback hell.

Create a promisifier for phaser signal

/**
 * Convert a phaser event(signal) to promise(for use with async/await)
 * @param awaitSignal Phaser Signal
 */
function signalAsync(awaitSignal: Phaser.Signal)
{
	return new Promise((resolve, reject) =>
	{
		awaitSignal.addOnce(() =>
		{
			resolve(awaitSignal);
		});
	}) as Promise<Phaser.Signal>
}

Usage for an array of animations

async function animateAsync(animationSequence: Phaser.Animation[])
{
	for (const animation of animationSequence)
	{
		await signalAsync(animation.play().onComplete)
	}
}

Besides the need for async await and Promise support/shim/transpile for some browsers, one major pitfall of this approach is it will hard to cancel if the chain gets big, probably has to create some kind of cancellation token which can be tedious.

2 Likes

That looks awesome. Either I gotta find a way to implement this in ES5 (hey, callback hell) or convert my project to ES6. And to Typescript…

Thanks for sharing your code!

Edit: Harder than I thought to convert this to ES5

I just thought of using recursion for ES 5. Not really sure if this works, not tested yet

/**
 * Recursively play from an array of animations.
 * @param {Phaser.Animation[]} sequence 
 */
function animateRecursive(sequence)
{
    var sequenceCopy = sequence.slice()
    var animation = sequenceCopy.shift()
    var signal = animation.play().onComplete
    if (sequenceCopy.length > 0)
    {
        signal.addOnce(function ()
        {
            animateRecursive(sequenceCopy)
        })
    }
}
1 Like

That looks pretty neat, thanks for that :slight_smile: