Dragging with ActionScript (AS3)

It's easy to find tutorials for drag and drop, and for hitting targets when you drop. It's a little more challenging to find a simple explanation of how to get the dragged object to stay inside the boundaries you would like it to observe. So here are three common cases for dragging: the horizontal bar, the vertical bar, and a rectangular space.

You need to upgrade your Flash player (v.9 or later) to view this example.

The solution to constraining the dragged object (or keeping it fenced in) is to create a virtual rectangle. Yeah, what the heck is that?

var bounds3 = new Rectangle(150, 100, 500, 250);

That's all it is. There is no visible rectangle at all. But the startDrag(); method is going to use what you defined:

freehandle_mc.startDrag(false,bounds3);

What's going on there? Well, false says the thing you are dragging will be "locked" to the mouse at the point where you clicked it. If you wrote true instead, the registration point of the dragged object would be "locked" to the mouse (and it jumps weirdly if you do that). The second part, bounds3, is what was defined in that variable above. It creates a "fence" that starts at 150 (x) and 100 (y) on the Stage; the width of the boundary area is 500, and the height of the boundary area is 250. So when we made the variable bounds3, we created a virtual rectangle with these attributes: x, y, width, height.

Why does the object go outside the bounds (which happen to be the same as the pink rectangle seen above)? That's one of the things that drives a newbie crazy. The boundaries you defined are being observed by the dragged object -- but those boundaries are relative to the object's registration point. So to keep it wholly inside (like the two skinny tracks in my example), you need to shave off the width and/or height of the dragged object. Or ... make a "magic" variable:

var magicWidth = trackbar_mc.width - handle_mc.width;

So for the horizontal track in my example, the virtual rectangle is defined like this:

var bounds = new Rectangle(0, 0, magicWidth, 0);

If you download the FLA, you'll find that the ActionScript is all in Frame 1 on the Timeline.

DOWNLOAD The files can be downloaded from this folder.

Education use: This package was created as an example for my journalism students. It is not intended to be used commercially.

Use and re-use: Drag Control in Flash CS4 or CS5 (AS3) by Mindy McAdams is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
Creative Commons License

Updated 5 March 2011