Simple Drag in AS 3.0
Here’s a really simple and fast example on how to use Drag in ActionScript 3.0. Not much has changed since ActionScript 2.0 when it comes to dragging objects around, just that now, things are much easier to use and we can write much more organized code when taking advantage of ActionScript 3.0’s OOP features.
MainClass.as which is set as a Document Class:
package { import com.wisebisoft.CustomCircle; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.MouseEvent; public class MainClass extends Sprite { // ---------------------------------------- // CONSTRUCTOR // ---------------------------------------- public function MainClass() { // Default stage settings stage.scaleMode = StageScaleMode.NO_SCALE; stage.showDefaultContextMenu = false; stage.align = StageAlign.LEFT; init(); } // ---------------------------------------- // Private Methods // ---------------------------------------- /** * Handles the application initialization; it creates a * CustomCircle instance passing in two values ( radius, color ) and * adds a MOUSE_DOWN and MOUSE_UP event listener to our newly * created circle; the two event listeners will handle the dragging. */ private function init():void { var circle:CustomCircle = new CustomCircle(100, 0x000000); circle.buttonMode = true; circle.x = 280; circle.y = 200; circle.addEventListener(MouseEvent.MOUSE_DOWN, startDragHandler); circle.addEventListener(MouseEvent.MOUSE_UP, stopDragHandler); this.addChild(circle); } /** * Starts dragging the targeted object. */ private function startDragHandler(event:MouseEvent):void { event.target.startDrag(); } /** * Stops dragging the targeted object. */ private function stopDragHandler(event:MouseEvent):void { event.target.stopDrag(); } } }
CustomCircle.as which is just a simple class that draws our custom circle:
package com.wisebisoft { import flash.display.Sprite; public class CustomCircle extends Sprite { // ---------------------------------------- // CONSTRUCTOR // ---------------------------------------- public function CustomCircle(radius:Number, color:uint) { drawCircle(radius, color); } // ---------------------------------------- // Private Methods // ---------------------------------------- /** * Draws a circle with the help of the arguments * that are passed to it. */ private function drawCircle(radius:Number, color:uint):void { this.graphics.beginFill(color, 1); this.graphics.drawCircle(0, 0, radius); this.graphics.endFill(); } } }
Of course, you can download the source files from here: Simple Drag

