Using the Tween class for drag and drop snap

The Tween class has many uses for enhancing interactions created with ActionScript code. We finish this tutorial with a completely different example to illustrate this point. The "Drag and Drop" interface is thoroughly addressed in another tutorial on the site (see Drag and Drop in Flash CS3 in the Basic section) but the "snapping" effect discussed there can be made much more effective using the Tween class. The example below illustrates the simplest version of the idea.


Download the well-commented fla file for the swf displayed above.

The Code

These import statements allow us to create and control tweens.

import fl.transitions.Tween;

import fl.transitions.easing.*;

Next we declare "tween" variables. Note that we must use one tween for each property of an object we wish to change over time. Since the example above shows movement in the x and y direction as well as a rotation, we will use three tweens.

var moveBackX:Tween;

var moveBackY:Tween;

var moveRound:Tween;

Create spirtes to serve as a holder and a draggable box and add the appropriate graphics. Note thatt we make the (0,0) point of the "dragger" in the center since we will be rotating it, and we make the (0,0) point of the holder 1 px off center to get a nice overlay effect.

var dragger:Sprite = new Sprite();

var holder:Sprite = new Sprite();,0);;,-25,100,50);;

dragger.x = 100;

dragger.y = 100;


holder.x = 100;

holder.y = 100;



We add listeners so that a "mouse down" on the box starts the drag but a "mouse up" anywhere stops the dragging.

dragger.addEventListener(MouseEvent.MOUSE_DOWN, goDrag);


addEventListener(MouseEvent.MOUSE_UP, goBack);

The goDrag function starts dragging the "dragger" box with an added drop shadow for effect.

function goDrag(evt:MouseEvent):void {


dragger.filters = [ new DropShadowFilter() ];


The goBack function removes the drop shadow and constructs three "tweens" to put the box back to the holder over a period of 0.5 seconds with a 180 degree rotation thrown in for a flourish. To see the syntax for the Tween constructor, see that help file for "Tween Class." See the help files for the "fl.motion.easing package" for other choices of easing functions.

function goBack(evt:MouseEvent):void {


dragger.filters = [ ];

moveBackX = new Tween(dragger, "x", Strong.easeOut, dragger.x, holder.x, 0.5, true);

moveBackY = new Tween(dragger, "y", Strong.easeOut, dragger.y, holder.y, 0.5, true);

moveRound = new Tween(dragger, "rotation", Strong.easeIn, 0, 180, 0.5, true);


Back to Basic Tutorials              Back to Flash and Math Home

We welcome your comments, suggestions, and contributions. Click the Contact Us link below and email one of us.

Adobe®, Flash®, ActionScript®, Flex® are registered trademarks of Adobe Systems Incorporated.