In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

Drag & Drop with AS3

  package {
    import flash.display.*;
    import flash.events.*; 

    public class DragDrop extends Sprite {
      private var obj:Sprite;
      private var offsetX:Number;
      private var offsetY:Number;

      public function DragDrop():void {
        var rettangoli:Array = new Array();
        for (var i:int = 0; i < 20; i++) {
          rettangoli[i] = new Sprite();
          rettangoli[i].graphics.lineStyle(1);
          rettangoli[i].graphics.beginFill(Math.floor(Math.random()*0xFFFFFF), 1);
          rettangoli[i].graphics.drawRect(0, 0, 100, 50);
          rettangoli[i].x = Math.floor(Math.random()*500);
          rettangoli[i].y = Math.floor(Math.random()*400);
          rettangoli[i].addEventListener(MouseEvent.MOUSE_DOWN, drag);
          rettangoli[i].addEventListener(MouseEvent.MOUSE_UP, drop);
          addChild(rettangoli[i]);
        }
      } 

      function drag( event  :  MouseEvent  ):void{
        var highestDepth:uint = numChildren - 1;
        obj = event.target as Sprite;
        setChildIndex(obj, highestDepth);
        offsetX = mouseX - obj.x;
        offsetY = mouseY - obj.y;
        stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveListener);
      }

      function drop( event  :  MouseEvent  ):void{
        stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveListener);
      }

      function mouseMoveListener( event  :  MouseEvent  ):void{
        obj.x = mouseX - offsetX;
        obj.y = mouseY - offsetY;
        event.updateAfterEvent();
      }

    }
  }