06
Jun
08

TweenLite Introduction

One of my favorite things to do in Flash is to program different types of motion. From particle systems to the boss at the end of an advergame—the basic principles for moving things around the screen with code are the same. There was a time when all the different types of motion that I saw happening—back in the Flash 4 days—were a complete mystery to me. I remember spending a long time reverse engineering open source examples from ultrashock.com.

Motion Myth

For some reason lots of people seem to think that ActionScript animation creates smoother animation than the Flash timeline. This is simply not true. The timeline is just as capable of creating "smooth" animations as ActionScript is.

On the timeline, if you want a smoother animation, use a framerate around 30fps and put more space between your keyframes.

ActionScript vs. Timeline

Students sometimes ask me when to use coded animation and when to use timeline animation. The answer is more complicated than you might expect. Here's a basic set of rules:

TIMELINE ANIMATION IS FOR:
- animation that is always the same (static animation)

ACTIONSCRIPT ANIMATION IS FOR:
- interactive animation
- random animation
- animation driven from an outside source like an rss feed
- complex, static physics simulations that would be hard to animate on the timeline
- complex interactive physics simulation
- time-based animation—that is, animation that always runs at the same speed independent of framerate

When I first started using Flash, I programmed all my animation and avoided the timeline completely. This approach had an upside and a downside. The upside was that I learned a whole lot about making things move on the screen with code. The downside was that coding static animation is generally more time consuming then doing it on the timeline. Since coding static animations can be a good learning experience, I always tell my students to abide by the above list, but that the real choice of using ActionScript or timeline animation is up to them.

First Encounter With TweenLite

Until recently I had steered clear of all tweening engines for no reason in particular other than that I understood all the inner workings of them and would usually just write out motion math from memory when needed. A few months ago I was working as a consultant on a project with a few designers and a programmer. I knew that the designers liked to use tweening engines like Fuse, Tweener and TweenLite. I figured since they were using them, I should become familiar with them. I had also recently seen a graph about the speed of different tweening engines and made a note to myself to check out TweenLite. After a 5-minute explanation from a designer, I was up and running with TweenLite. I thought it was cool, but didn't think I'd find myself using it regularly.

When I got home that night I felt like playing with it a little more and I created this.

Download: TweenLite Play  Download TweenLite Play (12.8 KB, 4,493 hits)

The source for this is a bit advanced, I recommend reading through this post before playing with this file.

I had a class the following day and I decided to add a short TweenLite demo into the lesson plan. It was about this point that I started to realize the potential power of TweenLite. The library is so elegantly designed that my students picked it up almost immediately.

What is Time Based Animation?

TweenLite creates time-based animation. This means that if you tell a tween to last 2 seconds. It will always last 2 seconds no matter what framerate the SWF happens to be playing at. When a SWF runs on a slow computer it might not be able to run at the framerate you intended. If your SWF has timeline animation, the animation will look like its playing in slow motion. If your animation is time-based (like TweenLite), it will appear more choppy, but will still run at the same speed:

This movie requires Flash Player 9. Please update your player.

Move the fps slider to see the difference between a TweenLite frame-based tween and a normal Flash timeline tween. Note that the frame-based tween continues to take approximately 2 seconds to complete at any framerate. Whereas the Flash timeline tween is entirely dependent on the framerate of the SWF.

Getting Started

The first thing you need to do to start working with TweenLite is to download it. Extract the zip and grab the "gs" folder. You can put it in your classpath or you can just place it next to your FLA. Once you've done either of those two things you'll be ready to go.

In order to use TweenLite we need to import it. TweenLite uses the same static easing functions that Flash's internal tweening engine uses, so when using TweenLite we generally have two import statements:

import gs.TweenLite;
import fl.motion.easing.*;

Add that code to your timeline, draw a box on your stage and convert it to a movie clip. Give it an instance name of box and add one more line of code to your timeline:

TweenLite.to(box,2,{x:400});

Make sure your box is somewhere on the left hand side of the stage and then test your movie. If you've done everything correctly, your box should move to 400 on the x axis. The TweenLite.to() method is really handy and very easy to understand. It takes three arguments. The first is the display object to tween. The second is how long the tween should take, and the third is an object that tells TweenLite which properties to tween.

Let's change our call to TweenLite.to() a little bit:

TweenLite.to(box,3 ,{x:400, rotation:180, scaleX:2, scaleY:2});

This time, we tell our tween to last three seconds and we start playing with more than one property at a time. We move to 400 on the x, rotate to 180 and scale the movie clip up to 200%. Test your movie and have a look.

By default TweenLite uses a quadratic ease out equation. All the different types of tweens we can use are defined in the fl.motion.easing package:

The third argument of the TweenLite.to() method has a few special properties that give us more control over the tween. The first one is ease, this is where we use the functions from the fl.motion.easing package. Try a couple different values to get a feel for the different types of easing:

// note that most tweens have an easeOut, easeIn and easeInOut constant.

// easeOut
TweenLite.to(box,3 ,{x:400, rotation:180, scaleX:2, scaleY:2, ease:Bounce.easeOut});

// easeIn
TweenLite.to(box,3 ,{x:400, rotation:180, scaleX:2, scaleY:2, ease:Bounce.easeIn});

// easeInOut
TweenLite.to(box,3 ,{x:400, rotation:180, scaleX:2, scaleY:2, ease:Bounce.easeInOut});

Just understanding the way these few aspects of TweenLite work is enough to start using it for basic applications. At this point you might want to take a break and play around with the TweenLite.to() method.

Continuing...

After playing around a bit, I wondered how to use one type of tween on the x axis and another type of tween on the y. This is easily accomplished with the overwrite property. Try this code in your timeline:

ActionScript 3.0:
  1. import gs.TweenLite;
  2. import fl.motion.easing.*;
  3.  
  4. box.x = 150;
  5. box.y = 150;
  6.  
  7. TweenLite.to(box, 2,{x: 300});
  8. TweenLite.to(box, 2,{y: 300, ease:Bounce.easeOut, overwrite:false});

The above creates a gravity effect by combining the default quadratic tween with the Bounce.easeOut function. Because the overwrite property is false, the second tween doesn't overwrite the first tween. Instead, it tweens independently.

After playing with the overwrite property for awhile, I wanted to run another function after the tween was complete. This is done by setting the onComplete property. Try running this code in your timeline:

ActionScript 3.0:
  1. import gs.TweenLite;
  2. import fl.motion.easing.*;
  3.  
  4. box.x = 150;
  5. box.y = 150;
  6.  
  7. TweenLite.to(box, 2,{x: 300});
  8. // here we define our onComplete callback function
  9. TweenLite.to(box, 2,{y: 300,
  10.                                ease:Bounce.easeOut,
  11.                                overwrite:false,
  12.                                onComplete: onJump});
  13.  
  14. function onJump():void {
  15.     TweenLite.to(box, 1,{y: 100, rotation:180, ease:Back.easeOut});
  16. }

After doing this I assumed there must be an easy way to pass parameters to your onComplete function. For this task, there's another property called onCompleteParams which takes an array of arguments to pass to the onComplete function. This means that you can have a bunch of objects that all use the same onComplete function. So, if we didn't want to specifically reference box in our onJump function, we could replace lines 9-16 of the previous script with the following:

TweenLite.to(box, 2,{y: 300,
           ease: Bounce.easeOut,
           overwrite: false,
           onComplete: onJump,
           onCompleteParams: [box]});

function onJump(mc:MovieClip):void {
	TweenLite.to(mc, 1,{y: 100, rotation:180, ease:Back.easeOut});
}

Relative Positioning

There are three more extremely useful parts of TweenLite worth mentioning. The first one is really simple. If you pass a string to a property rather than a numeric value, that tells TweenLite to use relative positioning. So if you write:

  TweenLite.to(box, 1,{y: 100});

Your telling TweenLite to set the y position of box to 100. But if you write:

  TweenLite.to(box, 1,{y: "100"});

Your telling TweenLite to add 100 pixels to the current y position of box. Try this code out:

ActionScript 3.0:
  1. import gs.TweenLite;
  2. import fl.motion.easing.*;
  3.  
  4. stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown, false, 0, true);
  5.  
  6. function onDown(evt:MouseEvent):void {
  7.     TweenLite.to(box, 1, {x:"40", ease:Elastic.easeOut});
  8. }

Every time we click the stage, the box eases 40 pixels to the right.

Delay

The delay property simply adds a delay before your tween starts. Consider the following code:

TweenLite.to(box, 1, {x:300});
TweenLite.to(box, 1, {y:300, overwrite:false, delay:.5})
TweenLite.to(box, .5, {scaleX:.5, overwrite:false, delay:.9})

We combine three tweens but start them at different times. The result is that the box moves right, then left and then towards the end of the tween, the box scales to 50% width. The delay property is really nice for creating short sequences of events.

From Method

The TweenLite.from() method works just like the TweenLite.to() method except that it tweens from the specified values in your third argument rather than to them. I've found this very useful for intro animations. You can just lay all your movie clips on the stage where you want them to end up - then add some TweenLite code to tween them into position. Take a look at this example:


click on this SWF to replay the animation

This movie requires Flash Player 9. Please update your player.

Download: Fake Banner  Download Fake Banner (11.9 KB, 2,764 hits)

You might want to download the FLA above and take a look at it. All the movie clips have just been placed on the stage exactly where I want them to end up. I then use TweenLite.from() to animate them:

ActionScript 3.0:
  1. import gs.TweenLite;
  2. import fl.motion.easing.*;
  3.  
  4. stop();
  5.  
  6. // notice this handy tint property, which allows us to
  7. // fade from black ... we have to use 0x000001 because if we
  8. // pass 0x000000 (or 0) to tint it thinks we want to reset it
  9. TweenLite.from(bg,1,{tint:0x000001});
  10.  
  11. TweenLite.from(logoBg, 1,{scaleX:0,
  12.                           scaleY:0,
  13.                           ease:Back.easeOut,
  14.                           delay:.5});
  15.  
  16. TweenLite.from(logoBall0, 1,{scaleX:0,
  17.                              scaleY:0,
  18.                              ease:Elastic.easeOut,
  19.                              delay:1.5});
  20.  
  21. TweenLite.from(logoBall1, 1,{scaleX:0,
  22.                              scaleY:0,
  23.                              ease:Elastic.easeOut,
  24.                              delay:1.75});
  25.  
  26. TweenLite.from(logoBall2, 1,{scaleX:0,
  27.                              scaleY:0,
  28.                              ease:Elastic.easeOut,
  29.                              delay:2});
  30.  
  31. TweenLite.from(as3, 1,{x:-100,
  32.                        ease:Elastic.easeOut,
  33.                        delay:2});
  34.  
  35.  
  36.  
  37. stage.addEventListener(MouseEvent.CLICK, onAnimate,
  38.                        false, 0, true);
  39.  
  40. function onAnimate(evt:MouseEvent):void {
  41.     // reset all clip positions by going to a blank fram and letting
  42.     // the movie loop back to frame 1
  43.     play();
  44. }

It's this type of easily scripted animation that sold me on TweenLite. I really like the Flash timeline and use it for static animation 90% of the time - there are some types of animation that are just better done by hand. However, for simple things like the above example TweenLite is absolutely perfect.


It's important to note that you'll need to go to this link : http://blog.greensock.com/tweenliteas3/ and download TweenLite in order for any of the code in the post to work. It's also worth taking a look at the excellent documentation that you'll find at that same link.

More To Come

I'll be posting a few additional TweenLite examples in the near future. So be sure to check back.

Print This Post Print This Post


32 Responses to “TweenLite Introduction”


  1. 1 Jake Rutter Jun 12th, 2008 at 6:55 pm

    Great Post! I've been using TweenLite for a couple of months now on some projects and really love how easy it is to implement. I still have a lot to learn about using it in different ways, which Im sure I will only achieve with time/practice. Thanks for posting this!

  2. 2 Zevan Jun 12th, 2008 at 7:04 pm

    Thanks Jake. If you haven't already checked it out... the first source link in this post makes use of some more advanced TweenLite techniques.

  3. 3 Jake Rutter Jun 27th, 2008 at 6:32 pm

    I just checked out the link. But I have a question, I was reading in your book about the tween library within actionscript 3? Whats the difference between using tweenlite and the as3 version? It seems like the effects are similar.

  4. 4 Hudey Jun 28th, 2008 at 3:31 am

    Excellent post Zevan! I started playing with Tweenlite about the same time you did, and I really think that if the online display advertising market continues to grow, a lot of ad creators out there (like me!) should take a LONG HARD look at TweenLite... it's an indispensable tool for someone who needs a fast and, more importantly, lightweight tweening engine!

  5. 5 Sonic Jul 22nd, 2008 at 11:56 am

    Whoa! Cool! ActionScript 3.0 is awesome for game development!

  6. 6 DN Sep 14th, 2008 at 4:04 am

    Thanks for the lessons!

  7. 7 Joshua Van Patter Sep 23rd, 2008 at 3:18 am

    Hey Thanks, again for the post. I found it quite useful. Was wondering how much different TweenMax was from TweenLite?

    thanks,
    Josh

  8. 8 Mia Kalish Sep 24th, 2008 at 2:37 am

    I started using Tweenlite, with Zevan's extremely helpful introduction, this morning, and in a couple of hours, had a Very Sophisticated movie sequence for one of my new movies that showed Sherrington's metaphor of the brain coming awake after sleep. Very cool. Thanks so much. Book is great. Code actually works (not necessarily so in a lot of places!).

    Mia

  9. 9 most hacker Oct 3rd, 2008 at 3:09 am

    i'm a flash beginner ....... sorry for my stupid question... but in simple words what is TweenLite?
    and what the purpose of it ?

    thanks very much

  10. 10 Vlad Dec 31st, 2008 at 1:01 pm

    Thanks for the great post. Very helpful and easy introduction!
    Have anyboby heard about TweenMax? If yes, is it in any way better than TweenLite? Is it worth learning?

  11. 11 Rich Dec 31st, 2008 at 8:49 pm

    Vlad, TweenMax is essentially TweenLite's dad. Or, as Jack (the author of TweenLite) said, "TweenLite on steroids." TweenMax is TweenLite plus TweenFilterLite. The argument for using TweenLite or TweenFilterLite alone is that they are very small. The argument for using TweenMax is that everything is there when you need it. TweenMax is 11k. You can check it all out, here: TweenMax.

  12. 12 Alchemist Feb 25th, 2009 at 3:42 am

    Great post, sold me on TweenLite from Tweener. Though I like both, TweenLite certainly seems faster. However, I've noticed in some instances that tweens seem unusually choppy or slow. What is the greatest determinant of a tweens "lag?" In particular, I've noticed that height and width value tweens tend to run considerably slower than x,y value tweens. Do objects generated dynamically with code tween smoother than a MovieClip drawn on the time line?

  13. 13 Andy Feb 27th, 2009 at 12:19 am

    You realize the timing lines up if you set to the correct 30fps, right? 31 FPS is flash's ultimate misunderstanding, a hack for a Flash Player *6* *Mac only* bug that people are still for some reason using to this day. 31fps is nonsensical for normal usage, creates confusion with timing and fails to run properly at that speed anyway in a browser.

  14. 14 Zevan Feb 27th, 2009 at 1:01 am

    Yes Andy I realize this. 31 fps just became a habit from the days of flash 6. More recently I have just been using 30fps. But I've never experienced any issues with 31 fps.

  15. 15 kostya Mar 8th, 2009 at 1:45 pm

    thanks..this was very helpful...!

  16. 16 Matt McAlexander Apr 17th, 2009 at 1:54 pm

    I've learned so much from your book, and this tween tutorial is great! I have to completely redo my website now. haha

  17. 17 Dan Jun 3rd, 2009 at 7:47 pm

    This tutorial is a fantastic and very useful introduction to TweenLite, I had never really considered using it before reading this. 30mins later and I am very glad I did!

    Also considering buying your book now (nice plug... :D)

  18. 18 dope259 Jun 10th, 2009 at 4:47 pm

    love tweenlite and tweenmax in every way.. thanks for the introduction!!

  19. 19 ROB T Aug 13th, 2009 at 8:03 pm

    hi, was all clear enought until here...

    [b]
    The first thing you need to do to start working with TweenLite is to download it. Extract the zip and grab the "gs" folder. You can put it in your classpath or you can just place it next to your FLA. Once you've done either of those two things you'll be ready to go.[/b]

    what's my classpath?

    how do i place the gs folder next to my FLA?

    cheers

  20. 20 Rich Aug 18th, 2009 at 2:25 am

    Rob, your classpath is a preference setting that can be added either application-wide (Preferences) or per file (Publish Settings). If you're not yet using classpaths, start out with your second question. You can place the gs folder next to your FLA, by doing exactly what the words describe. That is, it's an operating system task, not a Flash or ActionScript task. Find the FLA you're editing. Let's say it's in a folder called "flash_tests" on your desktop. Then download the TweenLite package and extract it. Finally, place the "gs" folder next to, or in the same directory as, the FLA. This means the "gs" folder will also be in the "flash_tests" folder on your desktop. Unless you've accidentally removed or damaged your default classpaths, using the same folder will work because the folder that your FLA is in, no matter where that is, has already been added to Flash's classpaths as a relative address.

  21. 21 Emmanuel Lamptey Sep 14th, 2009 at 7:53 pm

    I love AS3. And thanks guys for the heads up!!! I love it.

  22. 22 Steve Sep 21st, 2009 at 6:59 am

    Hello,

    I am a student from AIO and working on my portfolio. I have been learning a lot just from your postings. I have a question about using tweenlite for a reverse frame animation.

    I have an animation with 50 frames at every 10 frames I have a stop action.
    I have two button forward and backward, the forward button plays the timeline till the next stop action. Then you press the forward button and again plays till the next stop action.

    I need the backward button to play the timeline in reverse order till it hits a stop()action

    Could you give any suggestion.

    THANKS YOU FOR ANY HELP!

  23. 23 Yarden Refaeli Oct 9th, 2009 at 5:55 am

    Thank you for this helpful guide! your blog design is AMAZING too =]
    Added to my iGoogle reader...

    -Yarden

  24. 24 Gayle Van Wely Oct 29th, 2009 at 3:04 am

    Will you be putting up some examples of the updated version v11.

    Looking forward to seeing some.

    Best,
    Gayle

  25. 25 Rich Oct 29th, 2009 at 5:01 am

    @Steve, Flash isn't optimized for playing the timeline backwards, so your performance may vary. Here's one way to do it. (This is a simplified example that doesn't use any buttons.)

    //frame 1
    var movement:String = "forward";
    
    this.addEventListener(Event.ENTER_FRAME, onEnter, false, 0, true);
    function onEnter(evt:Event):void {
    	if (movement == "forward") {
    		play();
    	} else if (movement == "backward") {
    		gotoAndStop(currentFrame-1);
    	}
    }
    
    //frame 10
    stop();
    movement = "backward";
    

    The file starts out in "forward" mode and just plays the timeline. When it reaches frame 10, the movement variable is set to "backward" and the file just goes to one frame at a time, the currentFrame - 1, unitil the variable is reset to again. In otherwords, every frame, you're telling the playhead to go to the frame before it.

    In your case, you can change the variable value with buttons or the frames in which you have stop actions.

  26. 26 Rich Oct 29th, 2009 at 5:02 am

    @Yarden, you're welcome!

  27. 27 Rich Oct 29th, 2009 at 5:05 am

    @Gayle, yes. I think both Zevan and I will write about the new version. I know I am planning a thing or two about it and, if I've correctly gauged Zevan's appreciation for the classes, he will probably follow up this great post with something new at some point.

  28. 28 Gayle Van Wely Nov 7th, 2009 at 3:48 am

    Awesome. I'm sure it will be great.

    Thank you!
    Gayle

  29. 29 priya Jan 29th, 2010 at 4:14 pm

    i need to mix 2 codes together but coming up with errors, i have to made tween object follow cursor and my code is

    // this creates tween
    public function startTween():void
    		{
    TweenLite.to( this, 2, { delay:1, x:getX(this), y:getY(this), ease:Elastic.easeOut, onComplete:startTween} );
    				}else{
    TweenLite.to( this, 2, { delay:1, x:x, y:y, ease:Elastic.easeOut, onComplete:startTween} );
    				}
    			//}
    		}
    

    this code makes object follow curser, how can i join it in above code so it comes without errors

    ball_mc.onEnterFrame = function() {
    	var xMouse = _root._xmouse;
    	var yMouse = _root._ymouse;
    	if(Math.abs(xMouse - this._x) < 1) {
    		this._x = xMouse;
    		this._y = yMouse;
    	} else {
    		this._x -= (this._x-xMouse) / 6;
    		this._y -= (this._y-yMouse) / 6;
    
  30. 30 Rich Feb 24th, 2010 at 9:56 pm

    @priya, I'm afraid you've got a bit of a mess on your hands there. THe first code is an excerpt from an AS3 class, and the second excerpt is from an AS2 procedural script. You'll have to update your second snippet to AS3 and then choose whether you want a class or a function.

    As a start, I can guess at an AS3 version of the second snippet, although this is definitely untested:

    addEventListener(Event.ENTER_FRAME, onFrameEnter, false, 0, true);
    function onFrameEnter(evt:Event):void {
    	var xMouse:Number = mouseX;
    	var yMouse:Number = mouseY;
    	if (Math.abs(xMouse - ball_mc.x) < 1) {
    		ball_mc.x = xMouse;
    		ball_mc.y = yMouse;
    	} else {
    		ball_mc.x -= (ball_mc.x-xMouse) / 6;
    		ball_mc.y -= (ball_mc.y-yMouse) / 6;
    	}
    }
    
  31. 31 subbu Jun 21st, 2010 at 4:51 pm

    Awesome. I just started learning Flash/ActionScript3.0 the hard way. This was a real nice article on tweening. Looking forward for more of these.

    subbu

  32. 32 Parasar Aug 16th, 2010 at 12:52 pm

    Thanks for the excellent examples. looking forward to others.

Leave a Reply




Speaking



Archives