Flash Drag and Drop Tutorial | startDrag Actionscript

    I find that Drag and Drop is the most intuitive form of user interaction (at least using a mouse). Actionscript has some of this functionality built in, with the interactive functions startDrag and stopDrag, these can help make our coding pretty easy. If you are transitioning from as2, the code was incredibly simple:

    Actionscript2

    on (press) {
        startDrag (this);
    }
    on (release, releaseOutside) {
        stopDrag ();
    }

    On the movie clip action panel you’d just put that script, which is actually pretty readable even if you don’t know code. The releaseOutside is to keep from the clip missing the release event, because sometimes if a user released the mouse button but was not currently over the clip being dragged for whatever reason, it will not stop dragging.

    Actionscript 3

    drag-drap-as3-ballSome things have changed with as3, other than the actual coding structure, the biggest change for me doing drag and drop in the new actionscript was that the mouse events have changed. There is no more a press or release. They were replaced with, MOUSE_DOWN and MOUSE_UP. There is no more releaseOutside either and this one is a little more complicated to find among the new MouseEvent list.
    Leaving it out works, but we still have the same problem. Check out the working example below and try dragging the red ball to the green or yellow one and drop it there. Since the green is above the red in the layer sequence, the mouse is over the green and when the MouseEvent.MOUSE_UP fires, it’s not on the red ball but on the green, so we don’t get to the code that drops the red ball. So the red ball code basically has times when the dragging sticks even after we release the mouse button. Not to mention the dragging is very jumpy!

    ballRed.addEventListener(MouseEvent.MOUSE_DOWN, dragRed);
    ballRed.addEventListener(MouseEvent.MOUSE_UP, dropRed);
    function dragRed(e:MouseEvent):void{
        ballRed.startDrag();
    }
    function dropRed(e:MouseEvent):void{
        ballRed.stopDrag();
    }

    Using the Mouse Move event will help us to customize our behavior a bit more. Plus I wanted to get a more abstract level to it, so I could apply the event listeners to any display object and use the event properties to target the right clips. We begin the drag with the Mouse Down, and the create some other eventListeners for the stage that will watch the Mouse Move and Up events. So clicking on the green or yellow ball, fires the grabMe function which sets the me variable (which will hold any object) to the current target of the event, which should always be the object that you click. So we are using the same code for both the green and yellow ball. I’m a big fan of code consolidation and reuse, it takes a little more effort, but the code is much more clean and portable even. Then we add the event listeners for the stage on MOUSE_MOVE and MOUSE_UP. So first, mthe dragMe function, just says to update after event. This makes the animation smoother cause it only updates the display after the event completes it’s process. Then the drop me function is attached to the stage, so anywhere you release the mouse, the object will stop dragging, plus we remove the stage event listeners and add back the listener for the original object (me). Note the buttonMode property as well, this will make the cursor turn to a hand when you hover that object.

    ballYellow.addEventListener(MouseEvent.MOUSE_DOWN, grabMe);
    ballYellow.buttonMode = true;
    ballGreen.addEventListener(MouseEvent.MOUSE_DOWN, grabMe);
    ballGreen.buttonMode = true;

    var me:Object;
    function grabMe(e:MouseEvent):void{
        me = e.currentTarget;
        me.removeEventListener(MouseEvent.MOUSE_DOWN, grabMe);
        me.startDrag();
        stage.addEventListener(MouseEvent.MOUSE_MOVE, dragMe);
        stage.addEventListener(MouseEvent.MOUSE_UP, dropMe);
    }
    function dropMe(e:MouseEvent):void {
        stage.removeEventListener(MouseEvent.MOUSE_UP, dropMe);
        stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragMe);
        me.stopDrag();
        me.addEventListener(MouseEvent.MOUSE_DOWN, grabMe);
    }
    function dragMe(e:MouseEvent):void {
        e.updateAfterEvent();
    }

    This functionality is much smoother and then when I want to add more code to the dragging or dropping, I have a place to do it already!

    Example

    Get Adobe Flash player

    Source

    as3dragdrop-ball.fla

    This entry was posted in tutorial and tagged , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

    12 Comments

    1. samBrown
      Posted April 27, 2009 at 9:56 am | Permalink

      interesting example, I’ve run into this as well and had to use a work-around. Thanks for the tip

    2. Posted April 30, 2009 at 4:06 pm | Permalink

      Nice tutorial, I as well had to do a work around because I wasn’t happy with the performance, but your code was a little better.

    3. André
      Posted August 28, 2009 at 8:47 am | Permalink

      What i´ve made to correct this issue??

      I´ve made a class extending the Sprite or MovieClip with the function Drag, that automatically add the listener to the stage when the mouse is down over the object, and remove when the stage has a mouseup… also all you need to do is “myInstance.draggable=true;” to create a draggable object, and you have another parameters like: lockCenter, bounds, smoothDrag (e.updateAfterEvent), topLevel (when mouse is down and topLevel is true the object becomes the top level of the container)

    4. fedoo
      Posted December 1, 2009 at 5:26 pm | Permalink

      Hi,

      Is there neccessary to use “me” variable? Could we use just “this” instead?
      like -> this.startDrag(); etc.

      thanks

    5. Morgan
      Posted December 6, 2009 at 12:40 pm | Permalink

      Worked great for me. Thanks for the tutorial.

    6. Posted December 7, 2009 at 10:09 am | Permalink

      @fedoo – the “me” isn’t required I’ve had to use it a couple times to specify the object that is being dragged in different ways in the past, and I guess it just stuck. using this is chancy though because at different times this can mean different things… I try to at least always use event.currentTarget or something of the sort.
      Thanks!

    7. Best Flash Stock
      Posted July 6, 2010 at 11:24 am | Permalink

      Thanks for the tip, very useful, i was using different approach, but it is similar.

    8. Rakesh
      Posted August 26, 2011 at 11:06 am | Permalink

      i need circle will delete when i right click on cirlce. how it will be.

    9. Anand Meena
      Posted September 8, 2011 at 7:36 am | Permalink

      Hi, I tried in flash builder and it is working fine.
      Below is the code :-
      just copy and paste this code in .mxml component.

      //Import classes so you don’t have to use full names.
      public function start():void
      {
      a3.addEventListener(MouseEvent.MOUSE_DOWN,grabME);
      a3.buttonMode = true;

      a4.addEventListener(MouseEvent.MOUSE_DOWN,grabME);
      a4.buttonMode = true;

      a5.addEventListener(MouseEvent.MOUSE_DOWN,grabME);
      a5.buttonMode = true;

      a6.addEventListener(MouseEvent.MOUSE_DOWN,grabME);
      a6.buttonMode = true;

      a2.addEventListener(MouseEvent.MOUSE_DOWN,grabME);
      a2.buttonMode = true;

      }

      private var me:Object;
      public function grabME(e:MouseEvent):void
      {
      me = e.currentTarget;
      me.removeEventListener(MouseEvent.MOUSE_DOWN, grabME);
      me.startDrag();
      stage.addEventListener(MouseEvent.MOUSE_MOVE,dragMe);
      stage.addEventListener(MouseEvent.MOUSE_UP, dropMe);
      }

      public function dropMe(e:MouseEvent):void {
      stage.removeEventListener(MouseEvent.MOUSE_UP, dropMe);
      stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragMe);
      me.stopDrag();
      me.addEventListener(MouseEvent.MOUSE_DOWN, grabME);
      }

      public function dragMe(e:MouseEvent):void
      {
      e.updateAfterEvent();
      }

      Thanks for this nice tutorial :-)
      Best of luck for your next tutorial.

    10. Kylie
      Posted October 7, 2011 at 12:32 pm | Permalink

      Hi, I am doing a puzzle game. MOUSE_DOWN is to startDrag(); and MOUSE_UP is to stopDrag();. I also used x and y coordinates to snap and hold the puzzle piece into place once the piece goes over the invisible movie clip. It works for the first puzzle piece which snaps into place but when I want to move my other puzzle pieces it doesn’t allow it.

      Do I add removeEventListenr():? Because when I do it says “Incorrect number of arguements? Thanks for the help.

    11. Posted November 14, 2011 at 10:33 am | Permalink

      Dude

      Cheers for this, I’ve been getting strange interference to my keyboard events caused by a slider and this appears to have fixed the issue and makes for far smoother dragging.

    12. scollege
      Posted February 27, 2012 at 5:00 pm | Permalink

      Nice bit of code. FYI – you are able to drag the yellow and green circles off screen and lose their handle. The red circle stays within bounds, though.

    One Trackback

    1. By Video | Enjolt.com | Innovate for Success on April 25, 2009 at 2:17 pm

      [...] strong class=keywordFlex/strong optimization techniques and practices Open Enterprise 2009: Dion Flash Drag and Drop Tutorial | startDrag Actionscript – circlecube.com 04/24/2009 I find that Drag and Drop is the most intuitive form of user [...]

    Post a Comment

    Your email is never published nor shared. Required fields are marked *

    *
    *

    You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    • Recent Posts

      WordPress updates plugin directory

      New additions to the plugin directory include: favorites, incorporating support forums into it's own tab for each plugin as well as support stats being displayed! Great! I think we also need the ability to give plugins ratings and reviews (bonus points if it can be done from within a wordpress admin dashboard when installing plugins). [...]

      Short Head

      Use zipf's short head to tune your website rather than redesign the whole thing. To make a website successful it needs to meet the needs of the users. Find out what those needs are by using the short head philosophy to equate most searched things as the biggest needs of the users. Use personas to [...]

      Img Set?

      Great article at a list apart discusing the state of the industry regarding responsive images. This picks apart the set attribute of the img element from a surprisingly objective view coming from someone so close to the picture element. Insightful discussion about the principle behind the proposals than the actual solution too. If the working [...]

      Triudo

      A mesmerizing animated triangle-ish shape form. Embedded Link triduo triduo Tweet

      Git – the paradigm shift

      A great developer story about the differences on what Git is vs other version control and what Git is not. This is how we should learn it. I heard over and over that it was distributed, but never grasped what that meant, so here are a few links and explanations that will help unlearn version [...]

      Tweening Lib comes to Javascript!

      I'm very excited to share the news that the tween library from GreenSock (hands down the best tweening library I used in flash) is not ported for use in javascript! This will be great! I missed that simple syntax from as3 when animating javascript, and now I can have my cake and eat it too. [...]

      Responsive CSS Tricks

      Here are a few useful css tricks to remember when building responsive design sites from web designer wall Embedded Link 5 Useful CSS Tricks for Responsive Design Making the design to be responsive is very easy as shown in my Responsive Design in 3 Steps tutorial, but maintaining the elements to look aesthetically balanced on [...]

      Picture element of srcset attribute?

      Bruce details the reasons and story behind the srcset attribute which is now introduced as an alternative to the picture element. Some aspects of the attribute are nice (like the fact that it's an attribute and not a new element, so it's creating up new elements with for problems. It's adapting currently used elements to [...]

      SVG Preloader with Raphael JS

      Here's a very creative use of using a newly available technology. Using svg graphics which are very lightweight, for a website preloader. I like the animation used as well. Embedded Link Make a stylish preloader with SVG | Tutorial | .net magazine Many sites neglect users with slow connections. Ian Culshaw explains how to use [...]

      CSS3 Button/Icon set

      I've been secretly hoping to see a few of these pop up once the whole icon font idea spread through the nets. I really like this idea and it's a very nice implementation too! I only see some quality issues on a couple of the icons (such as youtube), but it's awesome and I hope [...]

    • Recent Comments

      Bruce Brownlee

      Bruce Brownlee

      Ah IE6. I'd have 2 more years of sleep without IE6. Margin doubling, no properties,...
      versaena

      versaena

      how to give color at runtime…… thank you
      Mobile Websites

      Mobile Websites

      I disagree, mobile websites are the future – desktop websites and mobile websites...
      Matt Fasick

      Matt Fasick

      That's cool. I like the ripple effect as well.
      Nico

      Nico

      hi! really great job guy! very impressive.. just a question… do u have a solution to do a refresh...
      Evan Mullins

      Evan Mullins

      Agreed! I've just seen some people get pretty heated about separating all functionality...