Drag and Drop Interaction

startDrag() is a very easy and very cool function in Actionscript. It allows you to enable dragging for any Symbol on the stage in your swf.

For example, you might want to create a slider or a scrollbar for a web application - these things can easily be made using startDrag(). Apart from that it can be used in games which actually isn't a novelty since I can remember quite vividly that I saw games employing drag and drop many many years ago (for example a game called "Glasses" where you could drag a pair of glasses that could see through... well, I guess I shouldn't write what;)).

 What are we going to create in this tutorial is a little Flash game where you can drag two objects around the stage. The key to success here is understanding that all you have to do is declare two functions: onPress and onRelease. They must for declared separately for each object.

In a moment you'll create this:

 

 

You should download the start file for this tutorial at the bottom.

OK, have you opened the fla file?

If so, you can go ahead and paste the code onto Frame 1.

tophat.onPress = function(){
startDrag(this, false);
}
tophat.onRelease = function(){
stopDrag();
}
light_saber.onPress = function(){
startDrag(this, false);
}
light_saber.onRelease = function(){
stopDrag();
}

Quick Explanation

So as I was saying it's a two-part thing:

1. Creating an onPress function.
The first word before the dot is the instance name of the object referred to. Between the curly brackets actions are specified - in our case we're telling Flash to start dragging the object whose name is stored in this.

tophat.onPress = function() {
startDrag(this);
};

2. Creating an onRelease function.
This time we're stopping all drag interactions. We don't need to specify the instance name.

tophat.onRelease = function() {
stopDrag();
};

Now that you're done, you should duplicate this piece of code and change the instance name appropriately.

Making it more advanced

Sometimes we would like to indicate that an object is being dragged. For example, by scaling it up on press and scaling it back on release. How can this be done?

Have a quick glance at this.

 

tophat.onPress = function(){
startDrag(this, false);
this._xscale = this._yscale = 110;
}
tophat.onRelease = function(){
stopDrag();
this._xscale = this._yscale = 100;
}

Yes, we're changing the xscale and yscale properties of the object. Other things we might decide to do are changing alpha or tint.

 

OK, so here we have it: we programmed a simple drag and drop interaction in Flash. I hope you enjoyed.

AttachmentSize
Start files and finished files55.4 KB
Average: 4.1 (23 votes)