Dec 03
I used to teach drag-n-drop funtionality using startDrag() and stopDrag() MovieClip methods. This is the easiest and fastest way but it tends to be choppy when the framerate is low. To solve this problem, you should employ MOUSE_MOVE event as shown in this tutorial by Flash and Math.
Their tutorial is great and I’ll use their concept in this article. But I don’t want the draggable object to snap to its center when dragging. I’ll put in a lockcenter option and a swapDepths() alternative.
Notes:
- We capture the broadcasted MOUSE_MOVE event from the stage and not from the draggable object. This ensures it will keep on dragging even if the mouse cursor moves outside the object. I guess Flash and Math already explained this.
- 1 is subtracted from numChildren because children are placed in an Array thus child index is length-1.
- updateAfterEvent() just makes things a lot smoother.
Here’s the code:
var object:Sprite;
var offsetX:Number;
var offsetY:Number;
var snapToCenter:Boolean = false;
for(var i:uint = 0; i < 20; i++)
{
var newColor:uint = Math.random() * 0xFFFFFF;
var newX:Number = Math.random() * stage.stageWidth;
var newY:Number = Math.random() * stage.stageHeight;
var newRadius:Number = Math.random() * 50 + 20;
var sprite:Sprite = new Sprite();
sprite.graphics.beginFill(newColor);
sprite.graphics.drawCircle(0, 0, newRadius);
sprite.graphics.endFill();
sprite.x = newX;
sprite.y = newY;
sprite.buttonMode = true;
sprite.addEventListener(MouseEvent.MOUSE_DOWN, drag);
sprite.addEventListener(MouseEvent.MOUSE_UP, drop);
addChild(sprite);
}
function drag(e:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_MOVE, move);
object = e.target as Sprite;
swap(e.target);
}
function drop(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, move);
}
function swap(o:*):void
{
var highestDepth:uint = numChildren - 1;
setChildIndex(o, highestDepth);
if(snapToCenter)
{
offsetX = 0;
offsetY = 0;
o.x = mouseX;
o.y = mouseY;
}
else
{
offsetX = o.x - mouseX;
offsetY = o.y - mouseY;
}
}
function move(e:MouseEvent):void
{
object.x = mouseX + offsetX;
object.y = mouseY + offsetY;
e.updateAfterEvent();
}

June 1st, 2008 at 6:38 am
i’m guessing not alot of comments posted cause your site is not easily found. Thanks for the tutorial. very good writing.
September 3rd, 2008 at 12:11 pm
[...] Read more [...]
October 22nd, 2008 at 8:42 am
this seems like what ive been looking for….but i will have to learn how to use it first…
salamat po!
October 25th, 2008 at 4:20 pm
hi im a nooby to as3 so from a beginners perspective this is a great script ! thanks!
one question though … how would I apply this method to a movie clip named bass_mc for example? and does the movie clip need to be on the stage or just in the library to activate it when the addChild method is passed through
i know this is probably a very silly question for someone as seasoned as yourself but would appreciate any help you can give …
Many Thanks