Drag the pieces of the puzzle
April 2nd, 2009 in Flash | 5 CommentsThe goal of this tutorial is to show you how you can simply let your user moves objects on the stage of a flash application by dragging them.
In our case today, we will create a puzzle so that the user can move the pieces to assemble it.
The picture used for the puzzle was created by Dave Joyce and taken from interfacelift.com
1. Download the source files and open drag-puzzle_begin.fla. We will start from this base.
2. You could see that the pieces of the puzzle are already placed on the layer “pieces”.
Each piece is a Movie Clip.
3. First give each move clip an instance name like p1_mc, p2_mc, p3_mc and so on…

4. On the timeline, create a new layer at the top, name it actions, and lock it.

5. Now you can add the actionscript code.
Select the first frame of the actions layer and open the actionscript panel (F9).
Paste the following code :
var pieces : Array = [p1_mc, p2_mc, p3_mc,
p4_mc, p5_mc, p6_mc,
p7_mc, p8_mc, p9_mc];
for (var i:int=0; i<pieces.length; i++) {
pieces[i].buttonMode = true;
pieces[i].addEventListener(MouseEvent.MOUSE_DOWN, startMove);
pieces[i].addEventListener(MouseEvent.MOUSE_UP, stopMove);
}
function startMove(evt:MouseEvent):void{
evt.target.startDrag();
}
function stopMove(evt:MouseEvent):void{
evt.target.stopDrag();
}
6. Let’s explain it. First we have declared an array that contains all the instance names of the puzzle pieces.
Next, with a “for loop”, we loop throught this array and for each element of this array we :
- set its button mode to true so that a hand cursor appear when the mouse is over it.
- then add listeners, one for the MOUSE_DOWN and one for the MOUSE_UP event.
The startMove function handles the MOUSE_DOWN event, by calling the startDrag method. We get the instance of the piece that have dispatched the event with event.target.
The stopMove function handles the MOUSE-UP event by calling the stopDrag method.
7. Test your application (Ctrl + Enter for Windows, Cmd + Enter for Mac) to see the puzzle in action.






May 23rd, 2009
Nice tutorial!
I love the effect and the fact that you can assemble it yourself
Thank you.
May 29th, 2009
id like to see what it can do with buttons… hmmm but good job
May 31st, 2009
Its really cool
Jul 21st, 2009
[...] Read tutorial [...]
May 14th, 2010
Can I just ask how did you make the puzzle elements? I mean, from the ready picture.