Create your own tween manager class in AS3

I publish this tutorial with the permission of Krasimir Tsonev, from Bulgaria, who runs krasimirtsonev.com (take a look at the light bulbs: don’t you think it can be done using a basic Box2D rope?). It’s an amazing tutorial with clean and well commented code that will guide you through the process of the creation of a custom tween manager class with AS3.

There are some features in Flash that we can’t work without. Tween classes are among the most used ones. They give you ability to animate objects without using the timeline, to change the animation fast and easy. The idea of these classes is very simple. That’s why I think that it is a good idea to have your own tween manager that you can modify to fit into your needs.

The basic structure of our tween manager:

package {
	import flash.display.MovieClip;
	public class TweenManager extends MovieClip {
		private var _objectToModify:Object;
		private var _properties:Object;
		public function TweenManager(objectToModify:Object, properties:Object) {
			_objectToModify = objectToModify;
			_properties = properties;
		}
	}
}

We are going to pass the object that we want to modify and the properties that we want to change. The idea is to create a function that calls every frame. All the magic will be done there. As you can see in the code below I created a public function – start, which adds listener for ENTER_FRAME event. So now we have a repeated method, i.e. loop.

package {
	import flash.display.MovieClip;
	import flash.events.Event;
	public class TweenManager extends MovieClip {
		private var _objectToModify:Object;
		private var _properties:Object;
		public function TweenManager(objectToModify:Object, properties:Object) {
			_objectToModify = objectToModify;
			_properties = properties;
		}
		public function start():void {
			addEventListener(Event.ENTER_FRAME, loop);
		}
		public function loop(e:Event):void {
		}
	}
}

What are we going to pass as properties parameter? I think it is a good idea to use JSON object, because it’s really flexible and we can add/remove properties really fast without changing anything in our class. Here is an example of the creation of an object from our tween class.

package {
	import flash.display.MovieClip;
	public class App extends MovieClip {
		public var clip:MovieClip;
		public function App() {
			var properties:Object = {x:{start:50,end:390,steps:100}};
			var t:TweenManager = new TweenManager(clip,properties);
			t.start();
		}
	}
}

There are two things that you have to notice. The first one is that you should have a movie clip on the stage that you can use for the tween. The second thing is the properties object. As you can see we are going to change the “x” property of the clip from 50 to 390 for 100 steps, i.e. 100 frames. To be able to do that we need the value of “x” for each one of these 100 frames. The function “calculateValues” will do that for us:

package {
	import flash.display.MovieClip;
	import flash.events.Event;
	public class TweenManager extends MovieClip {
		private var _objectToModify:Object;
		private var _properties:Object;
		public function TweenManager(objectToModify:Object, properties:Object) {
			_objectToModify = objectToModify;
			_properties = properties;
		}
		public function start():void {
			for (var i:* in _properties) {
				_properties[i].values = calculateValues(_properties[i].start,_properties[i].end,_properties[i].steps);
			}
			addEventListener(Event.ENTER_FRAME, loop);
		}
		public function loop(e:Event):void {
		}
		private function calculateValues(startPos:Number, endPos:Number, steps:Number):Array {
			var values:Array = [];
			for (var i:int=0; i

As you can see we are adding dynamically a new array for every property in our properties object. "values" is an array with all the values of "x" for each of these 100 frames. The last thing that we should make is to pass the values to our clip, i.e. to write the content of the "loop" method.

package {
	import flash.display.MovieClip;
	import flash.events.Event;
	public class TweenManager extends MovieClip {
		private var _objectToModify:Object;
		private var _properties:Object;
		public function TweenManager(objectToModify:Object, properties:Object) {
			_objectToModify = objectToModify;
			_properties = properties;
		}
		public function start():void {
			for (var i:* in _properties) {
				_properties[i].values = calculateValues(_properties[i].start,_properties[i].end,_properties[i].steps);
				_properties[i].valueIndex = 0;
				_properties[i].isItDone = false;
			}
			addEventListener(Event.ENTER_FRAME, loop);
		}
		public function loop(e:Event):void {// looping through the properties  
			for (var i:* in _properties) {// checking if the properties tween is done     
				if (! _properties[i].isItDone) {// checking if the current value is the last one            
					if (_properties[i].valueIndex == _properties[i].steps + 1) {// marking the tween as a done 
						_properties[i].isItDone = true;
					}
					else {// applying the value     
						_objectToModify[i] = _properties[i].values[_properties[i].valueIndex];// incrementing the values' index 
						_properties[i].valueIndex +=  1;
					}
				}
			}// checking if all the tweens are done   
			var areAllDone:Boolean = true;
			for (i in _properties) {
				if (! _properties[i].isItDone) {
					areAllDone = false;
				}
			}// if yes then remove the listener    
			if (areAllDone) {
				removeEventListener(Event.ENTER_FRAME, loop);
			}
		}
		private function calculateValues(startPos:Number, endPos:Number, steps:Number):Array {
			var values:Array = [];
			for (var i:int=0; i

Please notice lines 18 and 19. We added a flag (isItDone) that indicates when the tween is finished and "valueIndex", which we used to go through all the values.
When you run the flash you will see that the circle is moving from x=50 to x=390 for 100 frames. Let's add some other properties and see how it looks:

package {
	import flash.display.MovieClip;
	public class App extends MovieClip {
		public var clip:MovieClip;
		public function App() {
			var properties:Object = {x:{start:50,end:390,steps:70},y:{start:50,end:390,steps:70},rotation:{start:0,end:180,steps:30},alpha:{start:1,end:0.5,steps:10}};
			var t:TweenManager = new TweenManager(clip,properties);
			t.start();
		}
	}
}

We can change as many properties as we want and obviously to set different steps for each one of them.

Ok, the Tween class looks good so far but it isn't as cool as we wanted. It's because there is no easing. We used only a linear type of motion. To add other types we're going to use some maths by Robert Penner. We will just change the calculateValues method and it will support different types of motions. Here is the final version of the class:

package {
	import flash.display.MovieClip;
	import flash.events.Event;
	public class TweenManager extends MovieClip {
		private var _objectToModify:Object;
		private var _properties:Object;
		public function TweenManager(objectToModify:Object, properties:Object) {
			_objectToModify = objectToModify;
			_properties = properties;
		}
		public function start():void {
			for (var i:* in _properties) {
				_properties[i].values = calculateValues(_properties[i].start,_properties[i].end,_properties[i].steps,_properties[i].method);
				_properties[i].valueIndex = 0;
				_properties[i].isItDone = false;
			}
			addEventListener(Event.ENTER_FRAME, loop);
		}
		public function loop(e:Event):void {// looping through the properties          
			for (var i:* in _properties) {// checking if the properies twee it's done 
				if (! _properties[i].isItDone) {// checking if the current value is the last one    
					if (_properties[i].valueIndex == _properties[i].steps + 1) {// marking the tween as a done          
						_properties[i].isItDone = true;
					}
					else {// applying the value 
						_objectToModify[i] = _properties[i].values[_properties[i].valueIndex];// incrementing the values' index     
						_properties[i].valueIndex +=  1;
					}
				}
			}// checking if all the tweens are done 
			var areAllDone:Boolean = true;
			for (i in _properties) {
				if (! _properties[i].isItDone) {
					areAllDone = false;
				}
			}// if yes then remove the listener  
			if (areAllDone) {
				removeEventListener(Event.ENTER_FRAME, loop);
			}
		}
		private function calculateValues(startPos:Number, endPos:Number, steps:Number, mtd:String):Array {
			var arr:Array = new Array();
			var calcEndPos:Number;
			for (var i:Number=0; i<=steps; i++) {
				calcEndPos = (endPos-startPos);
				switch (mtd) {
					case "InBack" :
						arr[i] = Ease.InBack(i,startPos,calcEndPos,steps,1.70158);
						break;
					case "OutBack" :
						arr[i] = Ease.OutBack(i,startPos,calcEndPos,steps,1.70158);
						break;
					case "InOutBack" :
						arr[i] = Ease.InOutBack(i,startPos,calcEndPos,steps,1.70158);
						break;
					case "OutBounce" :
						arr[i] = Ease.OutBounce(i,startPos,calcEndPos,steps);
						break;
					case "InBounce" :
						arr[i] = Ease.InBounce(i,startPos,calcEndPos,steps);
						break;
					case "InOutBounce" :
						arr[i] = Ease.InOutBounce(i,startPos,calcEndPos,steps);
						break;
					case "InCirc" :
						arr[i] = Ease.InCirc(i,startPos,calcEndPos,steps);
						break;
					case "OutCirc" :
						arr[i] = Ease.OutCirc(i,startPos,calcEndPos,steps);
						break;
					case "InOutCirc" :
						arr[i] = Ease.InOutCirc(i,startPos,calcEndPos,steps);
						break;
					case "In" :
						arr[i] = Ease.In(i,startPos,calcEndPos,steps);
						break;
					case "Out" :
						arr[i] = Ease.Out(i,startPos,calcEndPos,steps);
						break;
					case "InOut" :
						arr[i] = Ease.InOut(i,startPos,calcEndPos,steps);
						break;
					case "InElastic" :
						arr[i] = Ease.InElastic(i,startPos,calcEndPos,steps,0,0);
						break;
					case "OutElastic" :
						arr[i] = Ease.OutElastic(i,startPos,calcEndPos,steps,0,0);
						break;
					case "InOutElastic" :
						arr[i] = Ease.InOutElastic(i,startPos,calcEndPos,steps,0,0);
						break;
					case "InExpo" :
						arr[i] = Ease.InExpo(i,startPos,calcEndPos,steps);
						break;
					case "OutExpo" :
						arr[i] = Ease.OutExpo(i,startPos,calcEndPos,steps);
						break;
					case "InOutExpo" :
						arr[i] = Ease.InOutExpo(i,startPos,calcEndPos,steps);
						break;
					case "Linear" :
						arr[i] = Ease.Linear(i,startPos,calcEndPos,steps);
						break;
					case "InLinear" :
						arr[i] = Ease.InLinear(i,startPos,calcEndPos,steps);
						break;
					case "OutLinear" :
						arr[i] = Ease.OutLinear(i,startPos,calcEndPos,steps);
						break;
					case "InOutLinear" :
						arr[i] = Ease.InOutLinear(i,startPos,calcEndPos,steps);
						break;
					case "InQuad" :
						arr[i] = Ease.InQuad(i,startPos,calcEndPos,steps);
						break;
					case "OutQuad" :
						arr[i] = Ease.OutQuad(i,startPos,calcEndPos,steps);
						break;
					case "InOutQuad" :
						arr[i] = Ease.InOutQuad(i,startPos,calcEndPos,steps);
						break;
					case "InQuart" :
						arr[i] = Ease.InQuart(i,startPos,calcEndPos,steps);
						break;
					case "OutQuart" :
						arr[i] = Ease.OutQuart(i,startPos,calcEndPos,steps);
						break;
					case "InOutQuart" :
						arr[i] = Ease.InOutQuart(i,startPos,calcEndPos,steps);
						break;
					case "InQuint" :
						arr[i] = Ease.InQuint(i,startPos,calcEndPos,steps);
						break;
					case "OutQuint" :
						arr[i] = Ease.OutQuint(i,startPos,calcEndPos,steps);
						break;
					case "InOutQuint" :
						arr[i] = Ease.InOutQuint(i,startPos,calcEndPos,steps);
						break;
					case "InSine" :
						arr[i] = Ease.InQuint(i,startPos,calcEndPos,steps);
						break;
					case "OutSine" :
						arr[i] = Ease.OutQuint(i,startPos,calcEndPos,steps);
						break;
					case "InOutSine" :
						arr[i] = Ease.InOutQuint(i,startPos,calcEndPos,steps);
						break;
					default :
						arr[i] = Ease.Linear(i,startPos,calcEndPos,steps);
						break;
				}
			}
			return arr;
		}
	}
}

And the usage:

package {
	import flash.display.MovieClip;
	public class App extends MovieClip {
		public var clip:MovieClip;
		public function App() {
			var properties:Object = {x:{start:50,end:390,steps:170,method:"OutBack"},y:{start:50,end:390,steps:170,method:"OutBounce"},rotation:{start:0,end:180,steps:300,method:"OutElastic"},alpha:{start:1,end:0.5,steps:100}};
			var t:TweenManager = new TweenManager(clip,properties);
			t.start();
		}
	}
}

Together with "start", "end" and "steps" we are passing a new property "method" which is used by the "calculateValues" function. The class "Ease" contains mathematics methods that calculate the values. No need to understand it, just have to know how to use it.

And this is an example:

You may need to reload the page to see it in action.

Of course the class is not fully functional. I mean there are no checks if some of the properties like "start" or "end" are missing. We can also add an ability to call a callback method when some of the tweens finish. It's just a basic manager that you can develop.

Download the source code.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers