Drag the pieces of the puzzle

April 2nd, 2009 in Flash

The 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.

View DemoDownload Source

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…

Screenshot

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

Screenshot

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.

  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Twitter


What you think ...

(4 Comments)

+ Add a Comment
  1. Evgeniy
    May 23rd, 2009

    Nice tutorial!

    I love the effect and the fact that you can assemble it yourself :)

    Thank you.

  2. kyle mogg
    May 29th, 2009

    id like to see what it can do with buttons… hmmm but good job

  3. Josh
    May 31st, 2009

    Its really cool

  4. Flash tutorials | Some Special Flash Effect | Lemlinh.com
    Jul 21st, 2009

    [...] Read tutorial [...]

Leave a Comment

Name (required)

E-mail (required, will not be published)

Website