Dragging and Dropping Objects with the Mouse : Drag Drop « Development « Flash / Flex / ActionScript






Dragging and Dropping Objects with the Mouse

 
package {
  import flash.display.Sprite;
  import flash.display.DisplayObject;
  import flash.events.MouseEvent;
  import flash.geom.Point;
  import flash.filters.DropShadowFilter;

  public class Main extends Sprite {
    
    private var _red:Sprite;
    private var _green:Sprite;
    private var _blue:Sprite;
    private var _white:Sprite;
    
    private var startingLocation:Point;
    
    public function Main(  ) {
      _red = new Sprite(  );
      _red.graphics.beginFill( 0xFF0000 );
      _red.graphics.drawRect( 0, 10, 10, 10 );
      _red.graphics.endFill(  );
      
      _green = new Sprite(  )
      _green.graphics.beginFill( 0x00FF00 );
      _green.graphics.drawRect( 0, 30, 10, 10 );
      _green.graphics.endFill(  );
      
      _blue = new Sprite(  );
      _blue.graphics.beginFill( 0x0000FF );
      _blue.graphics.drawRect( 0, 50, 10, 10 );
      _blue.graphics.endFill(  );
      
      _white = new Sprite(  );
      _white.graphics.beginFill( 0xFFFFFF );
      _white.graphics.drawRect( 20, 10, 50, 50 );
      _white.graphics.endFill(  );
      
      addChild( _red );
      addChild( _green );
      addChild( _blue );
      addChild( _white );  

      _red.addEventListener( MouseEvent.MOUSE_DOWN, pickup );
      _red.addEventListener( MouseEvent.MOUSE_UP, place );
      
      _green.addEventListener( MouseEvent.MOUSE_DOWN, pickup );
      _green.addEventListener( MouseEvent.MOUSE_UP, place );
      
      _blue.addEventListener( MouseEvent.MOUSE_DOWN, pickup );
      _blue.addEventListener( MouseEvent.MOUSE_UP, place );
    }
    
    public function pickup( event:MouseEvent ):void {
      startingLocation = new Point(  );
      startingLocation.x = event.target.x;
      startingLocation.y = event.target.y;
      
      event.target.startDrag(  );
      event.target.filters = [ new DropShadowFilter(  ) ];
      
      setChildIndex( DisplayObject( event.target ), numChildren - 1 );
    }
    
    public function place( event:MouseEvent ):void {
      event.target.stopDrag(  );
      event.target.filters = null;
      
      if ( event.target.dropTarget == _white ) {
        var color:uint;
        switch ( event.target ) {
          case _red: color = 0xFF0000; break;
          case _green: color = 0x00FF00; break;
          case _blue: color = 0x0000FF; break;
        }
        
        _white.graphics.clear(  );
        _white.graphics.beginFill( color );
        _white.graphics.drawRect( 20, 10, 50, 50 );
        _white.graphics.endFill(  );
      }
      
      event.target.x = startingLocation.x;
      event.target.y = startingLocation.y;
    }
    
  }
}

        








Related examples in the same category

1.Drag and drop a Sprite
2.Dragging and Dropping