O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dragging and Dropping Objects with the Mouse

Problem

You want to provide a drag-and-drop-style interface.

Solution

Use startDrag(), stopDrag() and dropTarget from the Sprite class to implement drag-and-drop behavior. Alternatively, extend the ascb.display.DraggableSprite class for visually smoother dragging behavior using the drag() and drop() methods.

Discussion

Creating drag-and-drop behavior is not as difficult as you might think. The Sprite class includes methods specifically for the purpose of drag and drop, namely startDrag() and stopDrag().

The startDrag() method can be called on any Sprite instance to have it follow the mouse around the screen, creating the dragging effect. To stop dragging, call the stopDrag() method on the Sprite instance. After the drag operation is complete, you can examine the dropTarget property of the Sprite to determine the object that the Sprite was dropped on. The value of dropTarget is useful for determining if a drop operation is valid (such as dropping a folder icon on a trashcan to delete it).

When calling startDrag(), you don’t have to specify any parameters; however, the method accepts up to two parameters. The parameters are:

lockCenter

When true the center of the Sprite is locked to the mouse position regardless of where the user pressed the mouse. When false the Sprite follows the mouse from the location where the user first clicked. The default value is false.

bounds

The Rectangle region where you want to constrain dragging. The Sprite ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required