How to Drag Objects With AS3
Creating a drag-and-drop functionality in ActionScript 3 (AS3) is a relatively straightforward undertaking. With just a few lines of code, you can drag and drop just about any element in Flash. The easiest way to implement drag-n-drop functionality is by the use of the MovieClip methods startDrag() and stopDrag(). This is usually a mouse event that is triggered inside the Flash application. The drag-and-drop functionality has many variations that can be used to implement different actions inside Flash.
Instructions
-
-
1
Open your Flash program and set up the objects to be used for this project. Draw or import the graphics or elements that you want to drag and set them up on the main stage. To import a ready-made object, select "File" "Import" "Import to Stage."
-
2
Convert the created or imported object to a symbol by clicking on it and pressing F8. In this case, name the object "ball_mc" and define it as a movie clip using the drop-down list provided. Note that the object will be referenced in AS3 code using this name.
-
-
3
Right click on "Layer 1" on the timeline and select "Insert Layer." Name the new layer "Actions."
-
4
Click on frame 1 on the "Actions" layer and press F9. Add the code below in the popup box:
ball_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
ball_mc.addEventListener(MouseEvent.MOUSE_UP, drop);
function drag(event:MouseEvent):void {
ball_mc.startDrag();
}
function drop(event:MouseEvent):void {
ball_mc.stopDrag();
}
-
5
Press "Ctrl + Enter" to test your drag-and-drop functionality.
-
1
Tips & Warnings
Dragged objects can be controlled by defining the boundaries beyond which the objects cannot cross. This limitation is achieved by defining the x,y, width and height parameters of the bounding area as shown by the code below:
//The x & y coordinates
var my_x:int=stage.stageWidth-ball_mc.width;
var my_y:int=stage.stageHeight-ball_mc.height;
//The height and width
var myWidth:int=0-my_x;
var myHeight:int=0-my_y;
//Create a new instance of the rectangle class with the coordinates above.
var boundArea:Rectangle=new Rectangle(my_x, my_y, myWidth ,myHeight);
//The mouse down and up event listeners
ball_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
ball_mc.addEventListener(MouseEvent.MOUSE_UP, drop);
//This function drags the object but limits to the stage boundaries.
function drag(event:MouseEvent):void {
ball_mc.startDrag(false,boundArea);
}
//This function releases the ball object.
function drop(event:MouseEvent):void {
ball_mc.stopDrag();
References
Resources
- Photo Credit Comstock/Comstock/Getty Images