Click and Drag Movie Symbol

Click and Drag Movie Symbol

Flash CS4 ActionScript 3.0 Tutorial

 

How to Allow User to Click-Drag Objects with Flash ActionScript

 

 

Clicking and dragging symbols is necessary for games and interactive movies. To move a symbol, the user clicks, then drags it to a new location on the stage.

Tutorial Elements

Movie Symbol with instance name dragObj_mc

 

Step One

Add an object to the stage.

Step Two

Convert the object to a Movie Symbol by pressing F8 and choosing Movie Clip for the type.

Step Three

Assign your Movie Symbol an instance name of dragObj_mc in the Properties panel.

Step Four

Add a new layer at the top and name it Actions.

Step Five

Option (PC-Alt) double-click the first frame of the Actions layer to open the Actions panel.

Step Six

Copy/Paste the following code to the ActionScript panel.

dragObj_mc.addEventListener(MouseEvent.MOUSE_DOWN, onDragStart);

function onDragStart(e:MouseEvent):void{

dragObj_mc.startDrag();

}

dragObj_mc.addEventListener(MouseEvent.MOUSE_UP, onDragStop);

function onDragStop(e:MouseEvent):void{

dragObj_mc.stopDrag();

}

Step Seven

Click the Auto Format button to format the code

Step Eight

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Click and drag the Movie Symbol to a new location on the stage.

Dissecting the Code

The first line of the code adds an event listener to the dragObj_mc and connects it to the function named onDragStart. The function is activated whenever the mouse is in the down position.

The second line adds a function that starts dragging the object. The startDrag() method causes the Movie Symbol to follow the mouse movements.

The remainder of the code does the same thing in reverse. In other words, when the mouse is in the up position, the dragging stops.

Following the Mouse

Another option besides dragging is to have the object follow the user's mouse. For more info, see topic, Movie Symbol Follows Mouse.

 

Stock Images