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(); }