Simple Drag in AS 3.0
October 25th, 2008 by Biro Barna
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 { public function MainClass() { stage.scaleMode = StageScaleMode.NO_SCALE; stage.showDefaultContextMenu = false; stage.align = StageAlign.LEFT; init(); } 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); addChild(circle); } private function startDragHandler(event:MouseEvent):void { event.target.startDrag(); } private function stopDragHandler(event:MouseEvent):void { event.target.stopDrag(); } } }
CustomCircle.as which is just a simple class that draws our custom circle which we’ll be interacting with:
package com.wisebisoft { import flash.display.Sprite; public class CustomCircle extends Sprite { public function CustomCircle(radius:Number, color:uint) { drawCircle(radius, color); } 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 example from here: Simple Drag
Posted in ActionScript 3.0