Flash drag and drop tutorial: Difference between revisions

The educational technology and digital learning wiki
Jump to navigation Jump to search
m (Text replacement - "<pageby nominor="false" comments="false"/>" to "<!-- <pageby nominor="false" comments="false"/> -->")
 
(11 intermediate revisions by 4 users not shown)
Line 1: Line 1:
{{Incomplete}}
{{Incomplete}}
<pageby nominor="false" comments="false"/>
<!-- <pageby nominor="false" comments="false"/> -->
== Overview ==
== Overview ==


Dragging and dropping objects is a popular brick in edutainment programs. This is part of [[Flash]] CS3 tutorials.
Dragging and dropping objects is a popular brick in edutainment programs. This is part of [[Flash]] CS3 tutorials. It is probably not suitable for Flash designers without any programming experience.


; Learning goals:
; Learning goals:
Line 39: Line 39:


== Introduction - simple dragging code ==
== Introduction - simple dragging code ==
The screenshot shows a simple dragging application, i.e. you can move around the circle and the rectangle.
[[image:flash-cs3-drag-and-drop-simple.png|thumb|600px|none|Most simple drag and drop]]


; Step 1 - Draw an object
; Step 1 - Draw an object
Line 44: Line 47:


; Step 2 - Transform it into a Movie Clip
; Step 2 - Transform it into a Movie Clip
* Select all if you got several objects, then assemble maybe
* Select the object (or if you created several objects for a drawing select them all)
* Right-click on the object
* Right-click on the object and create a movie symbol
* Give it a name in the properties panel !
* Give the instance a name in the properties panel !


; Step 3 - Adapt code below
; Step 3 - Adapt code below


[[image:flash-cs3-drag-and-drop-simple.png|thumb|600px|none|Most simple drag and drop]]
Dragging code is really simple and follows the same principles we encountered for example in the [[Flash button tutorial]].
 
* Associate an event listener with an event handler function. This time we listen to "mouse down" and "mouse up" events and for each we need to write a function that will do the dragging.  


<pre>
<source lang="actionscript">
// Register mouse event functions
// Register mouse event functions
blue_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
blue_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
Line 71: Line 76:
obj.stopDrag();
obj.stopDrag();
}
}
</pre>
</source>


; Results
; Results
* Admire the [http://tecfa.unige.ch/guides/flash/ex/drag-and-drop-intro/flash-cs3-drag-and-drop-intro.html result]
* Admire the [http://tecfa.unige.ch/guides/flash/ex/drag-and-drop-intro/flash-cs3-drag-and-drop-intro.html result (flash-cs3-drag-and-drop-intro.html)]
* Get the source from http://tecfa.unige.ch/guides/flash/ex/drag-and-drop-intro/ (files flash-cs3-drag-and-drop-intro.*)
* Get the source from http://tecfa.unige.ch/guides/flash/ex/drag-and-drop-intro/ (files flash-cs3-drag-and-drop-intro.*)


Line 93: Line 98:
; Step 3 - Action script code
; Step 3 - Action script code


<pre>
<source lang="actionscript">
// Register mouse event functions
// Register mouse event functions
blue_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
blue_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
Line 127: Line 132:
}
}


</pre>
</source>


; Results
; Results
Line 159: Line 164:
Code below is fairly awful since it lacks abstraction, but it has the advantage to use a minimal variety of AS3.
Code below is fairly awful since it lacks abstraction, but it has the advantage to use a minimal variety of AS3.


<pre>
<source lang="actionscript">
var hits = 0;
var hits = 0;


Line 220: Line 225:
}
}
}
}
</pre>
</source>


; Results
; Results
Line 232: Line 237:
Btw this is the first AS3 code that includes a tiny bit of programming I ever made (I probably also should type variables but then I am not a real programmer ....)
Btw this is the first AS3 code that includes a tiny bit of programming I ever made (I probably also should type variables but then I am not a real programmer ....)


<pre>
<source lang="actionscript">


var dict = new Dictionary ();
var dict = new Dictionary ();
Line 312: Line 317:
}
}
}
}
</pre>
</source>


; Results
; Results
Line 329: Line 334:
* Objects go back where they came from
* Objects go back where they came from


<pre>
<source lang="actionscript">
// Daniel K. Schneider - TECFA - sept 2007
// Daniel K. Schneider - TECFA - sept 2007
// Copyright: See http://edutechwiki.unige.ch/en/
// Copyright: See http://edutechwiki.unige.ch/en/
Line 439: Line 444:
}
}


</pre>
</source>


; Results
; Results
Line 495: Line 500:


* [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundMixer.html SoundMixer] (Adobe AS3 reference)
* [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundMixer.html SoundMixer] (Adobe AS3 reference)
== Tutorials ==
* [http://www.monkeyflash.com/flash/drag-and-drop-in-as3/ Drag and Drop in ActionScript 3.0] A very easy to follow tutorial on how to implement drag and drop in AS3 by MonkeyFlash.com. FLA file provided. ''(This link is not current any more)''
* An easy to follow [http://www.lynda.com/Flash-CS5-tutorials/flash-professional-cs5-code-snippets-and-templates-in-depth/Adding-drag-and-drop/72925-4.html tutorial] about ''drag and drop'' in Flash CS5 by lynda.com.
* An other very detailed tutorial (approximately 20 minutes) in 3 parts:
** Drag and Drop Tutorial in Flash CS5 - Actionscript 3 [http://www.youtube.com/watch?v=ALqGYMsRWxw (Part 1/3)]
** Drag and Drop Tutorial in Flash CS5 - Actionscript 3 [http://www.youtube.com/watch?v=1hR3CVIdfuY (Part 2/3)]
** Drag and Drop Tutorial in Flash CS5 - Actionscript 3 [http://www.youtube.com/watch?v=g1kvSTHkbtQ (Part 3/3)]
== Links ==
AS CS4 reference:
* [http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/Sprite.html#stopDrag() startDrag() and stopDrag()]




[[Category: Multimedia]]
[[Category: Technologies]]
[[Category: Authoring tools]]
[[Category: Flash]]
[[Category: Flash]]
[[Category: Tutorials]]
[[Category:Flash tutorials]]
[[fr:Flash tutoriel drag and drop]]

Latest revision as of 17:36, 22 August 2016

Overview

Dragging and dropping objects is a popular brick in edutainment programs. This is part of Flash CS3 tutorials. It is probably not suitable for Flash designers without any programming experience.

Learning goals
Learn how to create simple drag and drop programs with Flash 9 (CS3) components
Learn a little bit of Action Script 3
Prerequisites
Flash CS3 desktop tutorial
Flash drawing tutorial
Flash layers tutorial
flash button tutorial
ActionScript 3 interactive objects tutorial
Moving on
The Flash article has a list of other tutorials.
Flash Video component tutorial
Quality
This text should technical people get going and may not be good enough for self-learning beginners. It can be used as handout in a "hands-on" class. That is what Daniel K. Schneider made it for...
Level
It aims at beginners. More advanced features and tricks are not explained here.
Learning materials

Grab the various *.fla files from here:

http://tecfa.unige.ch/guides/flash/ex/drag-and-drop-intro/

Tip: This page contains more code than screen dumps. You should download the source code and play with it.

The executive summary
  • Draw something on the canvas
  • Transform it to a movie symbol (buttons don't work)
  • Assign an instance name
  • Instance_name.startDrag()
  • Instance_name.stopDrag()
  • Test if the object sits over another object (target) and then script some action.

Introduction - simple dragging code

The screenshot shows a simple dragging application, i.e. you can move around the circle and the rectangle.

Most simple drag and drop
Step 1 - Draw an object
  • Anything you like
Step 2 - Transform it into a Movie Clip
  • Select the object (or if you created several objects for a drawing select them all)
  • Right-click on the object and create a movie symbol
  • Give the instance a name in the properties panel !
Step 3 - Adapt code below

Dragging code is really simple and follows the same principles we encountered for example in the Flash button tutorial.

  • Associate an event listener with an event handler function. This time we listen to "mouse down" and "mouse up" events and for each we need to write a function that will do the dragging.
// Register mouse event functions
blue_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
blue_btn.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);

red_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
red_btn.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);

// Define a mouse down handler (user is dragging)
function mouseDownHandler(evt:MouseEvent):void {
	var object = evt.target;
	// we should limit dragging to the area inside the canvas
	object.startDrag();
}

function mouseUpHandler(evt:MouseEvent):void {
	var obj = evt.target;
		obj.stopDrag();
}
Results

Drag and drop over another object

The goals is to write a little Flash application that will tell the user whether he correctly dragged and dropped an object over another one.

Step 1 - Start from the file above
  • I.e. we want to have the user drag the red circle over the blue rectangle.
Step 2 - Add a text box

This textbox should initially display instruction, then display feedback: "made it" and "missed".

  • Use the Textool in the tools panel to enter the text.
  • Then in the properties panel, change the type to Dynamic Text.
Dynamic Text
Step 3 - Action script code
// Register mouse event functions
blue_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
blue_btn.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);

red_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
red_btn.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);

// Define a mouse down handler (user is dragging)
function mouseDownHandler(evt:MouseEvent):void {
	var object = evt.target;
	// we should limit dragging to the area inside the canvas
	object.startDrag();
}

function mouseUpHandler(evt:MouseEvent):void {
	var obj = evt.target;
	// obj.dropTarget will give us the reference to the shape of
	// the object over which we dropped the circle.
	var target = obj.dropTarget;
	// If the object exists AND it is the blue button, then we change
	// the text in the TextBox. 
	// Since obj.dropTarget is a Shape, we need its parent.
	if (target != null && target.parent == blue_btn)
	{
		textField.text = "Made it !!";
	}
	else
	{
		textField.text = "Missed :(";
	}
	obj.stopDrag();
}
Results
Improvements to be made
  • Styling of the textbox: You can do this with the filters panel. Click on the + sign to add filters and then play around with the options.
  • Move the red circle back to its initial position
  • Special effects maybe

Drag and match learning application - dumb version

The goal is to move objects to a textbox containing the first letter of its name. E.g. "Cat" should be moved to the "C" box. If there is a hit, the user will get some success message and can't move the object anymore. If he is done, he should get an extra message.

Step 1 - Create movie clips for object to be moved
  • As above with the red and blue circle
  • Each object should have an instance name
Step 2 - Create textboxes
  • Also as above
  • Create one for each object (E.g. a "C" for the cat, etc.)
  • Make sure they are dynamic and they have a name.
Step 3 - Foreground/Background

Make sure that the textboxes are in the background or the movie clips in the foreground. Otherwise a dropped object will not find its target.

  • Select all the movie clips, then right-click->Arrange->Bring to Front.
Step 3 - Write Action Script code

Code below is fairly awful since it lacks abstraction, but it has the advantage to use a minimal variety of AS3.

var hits = 0;

// Register mouse event functions

dog.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
dog.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
rocket.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
rocket.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
cat.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
cat.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
bat.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
bat.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);

// Define a mouse down handler (user is dragging)
function mouseDownHandler(evt:MouseEvent):void {
	var object = evt.target;
	// we should limit dragging to the area inside the canvas
	object.startDrag();
}

function mouseUpHandler(evt:MouseEvent):void {
	var obj = evt.target;
	// obj.dropTarget will give us the reference to the shape of
	// the object over which we dropped the circle.
	var target = obj.dropTarget;
	// If the target object exists the we ask the test_match function
	// to compare moved obj and target where it was dropped.
	if (target != null)
	{
		test_match(target, obj);
	}
	obj.stopDrag();
}

function test_match(target,obj) {
	// test if either one of the four pairs match
	if ( (target == box_c && obj == cat) ||
             (target == box_d && obj == dog) ||
	     (target == box_r && obj == rocket) ||
             (target == box_b && obj == bat) )
	{
		// we got a hit
		hits = hits+1;
		textField.text = "Yes ! You got one !";
		// make the object transparent
		obj.alpha = 0.5;
		// kill its event listeners - object can't be moved anymore
		obj.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
		obj.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
		// Test if we are done
		if (hits == 4)
		{
			textField.text = "Made it !!";
		}
	}
	else
	{
		textField.text = "Missed :(";
	}
}
Results

Drag and match learning application - better

Instead of writing an application just for four matching pairs, we can write code that is more general. This code only needs slight modifications to adapt to other named instances and text boxes and you can insert as little/many pairs you like. Just make sure that the target textboxes are in the background.

Btw this is the first AS3 code that includes a tiny bit of programming I ever made (I probably also should type variables but then I am not a real programmer ....)

var dict = new Dictionary ();

// =================== START USER Config =====================
// Insert as many "dict[text_box] = movie;" statements you like
//  Replace: text_box by the name of a matching dynamic text_box
//           movie by the name of movie instances users can move around.

dict[box_c] = cat;
dict[box_d] = dog;
dict[box_r] = rocket;
dict[box_b] = bat;
dict[box_a] = apple;

// Do NOT change/delete any other line. Also make sure to respect
// the syntax, e.g. dont forget the ";" at the end of each line.
// ===================== END USER Config ==================== 

var hits = 0; // counts succesful hits
var max = 0;  // used to compute dictionary length

// For each item in the dictionary we add event listeners
// "for each" will loop through the values ... not the keys

for each (var item in dict)
{
	item.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
	item.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
	item.buttonMode = true; //needed for the hand cursor to work
	max = max + 1;
}


// Define a mouse down handler (user is dragging)
function mouseDownHandler(evt:MouseEvent):void {
	var object = evt.target;
	// we should limit dragging to the area inside the canvas
	object.useHandCursor = true;
	object.startDrag();
}

function mouseUpHandler(evt:MouseEvent):void {
	var obj = evt.target;
	// obj.dropTarget will give us the reference to the shape of
	// the object over which we dropped the circle.
	var target = obj.dropTarget;
	// If the target object exists the we ask the test_match function
	// to compare moved obj and target where it was dropped.
	if (target != null)
	{
		test_match(target, obj);
	}
	obj.stopDrag();
}

function test_match(target,obj) {
	// test if the pairs match
	if (dict[target] == obj)
	{
		// we got a hit
		hits = hits+1;
		textField.text = "Yes ! You got one !";
		// make the object transparent
		obj.alpha = 0.5;
		// kill its event listeners - object can't be moved anymore
		obj.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
		obj.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
		// Test if we are done
		if (hits == max)
		{
		        // here we should play an animation
			textField.text = "Made it !!";
		}
	}
	else
	{
		textField.text = "Missed :(";
	}
}
Results
Improvements to be made
  • Make it more flashy when there is a hit / miss and when it's over.
  • Add sound. A child can not read instructions, but a parent could tell :)
  • Move the object back to its origin when there is a miss.

Drag and match learning application - still better

Our last version for now includes some more features.

  • It has sound (though the initial "talk" is missing)
  • Objects go back where they came from
// Daniel K. Schneider - TECFA - sept 2007
// Copyright: See http://edutechwiki.unige.ch/en/

var dict = new Dictionary ();

// =================== START USER Config =====================
// Insert as many "dict[text_box] = movie;" statements you like
//  Replace: text_box by the name of a matching dynamic text_box
//           movie by the name of movie instances users can move around.

dict[box_c] = cat;
dict[box_d] = dog;
dict[box_r] = rocket;
dict[box_b] = bat;
dict[box_a] = apple;

// Do NOT change/delete any other line. Also make sure to respect
// the syntax, e.g. dont forget the ";" at the end of each line.
// ===================== END USER Config ==================== 

// Sound
// should I preload this somehow ?

var request:URLRequest = new URLRequest("applause_3.mp3");
var applause:Sound = new Sound();
applause.load(request);

var request2:URLRequest = new URLRequest("music.mp3");
var music:Sound = new Sound();
music.load(request2);

var request3:URLRequest = new URLRequest("baby_laugh.mp3");
var laugh:Sound = new Sound();
laugh.load(request3);

// Drag and match code
var hits = 0; // counts succesful hits
var max = 0;  // used to compute dictionary length

var ori_x;
var ori_y;

// For each item in the dictionary we add event listeners
// "for each" will loop through the values ... not the keys

for each (var item in dict)
{
	item.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
	item.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
	max = max + 1;
	item.buttonMode = true;
}


// Define a mouse down handler (user is dragging)
function mouseDownHandler(evt:MouseEvent):void {
	var object = evt.target;
	ori_x = object.x
	ori_y = object.y
	object.useHandCursor = true;
	object.startDrag();
}

function mouseUpHandler(evt:MouseEvent):void {
	//stop all sounds
	SoundMixer.stopAll();
	var obj = evt.target;
	// obj.dropTarget will give us the reference to the shape of
	// the object over which we dropped the circle.
	var target = obj.dropTarget;
	// If the target object exists the we ask the test_match function
	// to compare moved obj and target where it was dropped.
	if (target != null)
	{
		test_match(target, obj);
	}
	obj.stopDrag();
}


function test_match(target,obj) {
	// test if the pairs match
	if (dict[target] == obj)
	{
		// we got a hit
		hits = hits+1;
		textField.text = "Yes ! You got one !";
		applause.play();
		// make the object transparent
		obj.alpha = 0.5;
		// kill its event listeners - object can't be moved anymore
		obj.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
		obj.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
		// Test if we are done
		if (hits == max)
		{
			textField.text = "Made it !!";
			music.play(0,5);
		}
	}
	else
	{
		obj.x = ori_x;
		obj.y = ori_y;
		textField.text = "Missed :(";
		laugh.play();
	}
}
Results
Improvements to be made
  • Add a restart button
  • Rewrite this as an ActionScript 3 application that would take random pairs and play several scenes
  • The word of an object should be told aloud when the user picks it up
  • etc ....

Reference

I may move these to some other article sometimes soon.

Sprites and DisplayObjects

Objects that you can drag around are Movie Clips. These are children of Sprites. Sprites have associated graphics.

From the ActionScript 3.0 Language and Components Reference:

The class hierarchy looks like this: MovieClip -> Sprite -> DisplayObjectContainer -> InteractiveObject -> DisplayObject -> EventDispatcher -> Object

When you drop a sprite over another sprite, the Flash will give the shape of the target object. This shape is a DisplayObject and from a DisplayObject we can get its parent, i.e. a Movie Clip in our case.

Important: When you look at the definition of Class, there are buttons to open inherited properties and methods. Mostly likely you need these.

Event Listener Interface

Movie clips can use normal Event Handling:

Graphics

Dictionaries

TextFields

The TextField class is used to create display objects for text display and input.

Sounds

  • Sound (Adobe AS3 reference)

Tutorials

  • Drag and Drop in ActionScript 3.0 A very easy to follow tutorial on how to implement drag and drop in AS3 by MonkeyFlash.com. FLA file provided. (This link is not current any more)
  • An easy to follow tutorial about drag and drop in Flash CS5 by lynda.com.
  • An other very detailed tutorial (approximately 20 minutes) in 3 parts:
    • Drag and Drop Tutorial in Flash CS5 - Actionscript 3 (Part 1/3)
    • Drag and Drop Tutorial in Flash CS5 - Actionscript 3 (Part 2/3)
    • Drag and Drop Tutorial in Flash CS5 - Actionscript 3 (Part 3/3)

Links

AS CS4 reference: