Dragging Methods with ActionScript 3

February 6, 2009 by: smonte

This tutorial is all about dragging an object around the stage. You will learn different ways to implement dragging. I’ll also show you how to add some animation with the dragging. So start your Flash IDE and let’s get going!

ActionScript 3 startDrag and stopDrag methods

The methods startDrag and stopDrag are probably the most easiest methods to implement dragging. Follow these steps and see yourself!

1. Create a new document of size 400×400.

2. Draw a ball of size 80×80 to the center of the stage.

3. Convert the ball into a movie clip called “ball”. Set the registration point to the center.

4. Create a layer for ActionScript and type the following.

//Add event listeners for the MOUSE_DOWN and MOUSE_UP
//events, so we know when to start/stop dragging.
ball.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
ball.addEventListener(MouseEvent.MOUSE_UP, mouseReleasedHandler);
 
//This function is called when the user presses the mouse on the ball
function mouseDownHandler(e:MouseEvent):void {
    ball.startDrag();
}
 
//This function is called when the user releases the mouse
function mouseReleasedHandler(e:MouseEvent):void {
    ball.stopDrag();
}

Now test your movie. You now have a draggable object on the stage!

NOTE: If you want to snap the center of the ball to the mouse position when dragging, replace the mouseDownHandler with the following.

//This function is called when the user presses the mouse on the ball
function mouseDownHandler(e:MouseEvent):void {
    ball.startDrag(true);
}

That’s the basics of ActionScript 3 dragging. As you see, the dragging effect looks quite boring. Why not add some animation to it?

ActionScript 3 dragging with simple movement

The next piece of code moves the circle to the cursor’s coordinates in a constant speed when dragging. Erase the old ActionScript code and type the following.

//This variable tells whether the user is dragging or not
var dragging:Boolean = false;
 
//x and y speeds
var speedX:Number = 0;
var speedY:Number = 0;
 
//Overall speed
var speed:Number = 10;
 
//Add event listeners for the MOUSE_DOWN and MOUSE_UP
//events, so we know when to start/stop dragging.
ball.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseReleasedHandler);
 
//Add ENTER_FRAME which animates the ball movement
addEventListener(Event.ENTER_FRAME, moveBall);
 
//This function is called when the user presses the mouse on the ball
function mouseDownHandler(e:MouseEvent):void {
        dragging = true;
}
 
//This function is called when the user releases the mouse
function mouseReleasedHandler(e:MouseEvent):void {
        dragging = false;
}
 
function moveBall(event:Event):void {
 
        //We only move the ball when the user is dragging
        if (dragging) {
 
                //Calculate the x and y distances from the ball to the mouse
                var distanceX:Number = mouseX - ball.x;
                var distanceY:Number = mouseY - ball.y;
 
                //Calculate the distance from the mouse to the ball
                var dist = Math.sqrt(distanceX*distanceX + distanceY*distanceY);
 
                //If the distance is larger than 5, we move the ball
                if (dist > 5) {
                        //Calculate the angle from the ball to the mouse
                        var angle:Number = Math.atan2(distanceY, distanceX);
 
                        //Calculate the new x and y speeds
                        speedX = Math.cos(angle) * speed;
                        speedY = Math.sin(angle) * speed;
 
                        //Move the ball to the new coordinates (closer to the mouse)
                        ball.x += speedX;
                        ball.y += speedY;
                }
        }
}

Test your movie and you should have the same animation as seen below.

Dragging with spring

The next piece of code applies a spring effect to the dragging. Erase the old ActionScript code and type the following.

//This variable tells whether the user is dragging or not
var dragging:Boolean = false;
 
//Spring variable (how strong the spring effect is)
var springFactor:Number = 0.2;
 
//Friction for the animatiom
var friction:Number = 0.9;
 
//x and y speeds
var speedX:Number = 0;
var speedY:Number = 0;
 
//acceleration for x and y speeds
var accX:Number = 0;
var accY:Number = 0;
 
//Overall speed
var speed:Number = 10;
 
//Add event listeners for the MOUSE_DOWN and MOUSE_UP
//events, so we know when to start/stop dragging.
ball.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseReleasedHandler);
 
//Add ENTER_FRAME which animates the ball movement
addEventListener(Event.ENTER_FRAME, moveBall);
 
//This function is called when the user presses the mouse on the ball
function mouseDownHandler(e:MouseEvent):void {
        dragging = true;
}
 
//This function is called when the user releases the mouse
function mouseReleasedHandler(e:MouseEvent):void {
        dragging = false;
}
 
function moveBall(event:Event):void {
 
        //We only move the ball when the user is dragging
        if (dragging) {
 
                //Calculate the x and y distances from the ball to the mouse
                var distanceX:Number = mouseX - ball.x;
                var distanceY:Number = mouseY - ball.y;
 
                //Update x and y accelerations
                accX = distanceX * springFactor;
                accY = distanceY * springFactor;
 
                //Add the acceleration to the speed
                speedX += accX;
                speedY += accY;
 
                //Add friction, otherwise the animation
                //would go on forever.
                speedX *= friction;
                speedY *= friction;
 
                //Move the ball to the new coordinates (closer to the mouse)
                ball.x += speedX;
                ball.y += speedY;
        }
}

Test your movie!

Things are looking much more interesting now, don’t you think? In the next page, I’ll show you how to add a trail effect to the spring dragging.

  • Digg
  • Sphinn
  • del.icio.us
  • Mixx

Related tutorials:

  1. Movie Clip Trail Effect
  2. Particle Fountain with ActionScript
  3. Physics with ActionScript 3
  4. Rotating Mouse Trail with ActionScript 3
  5. Interactive Rocket

Comments

7 Responses to “Dragging Methods with ActionScript 3”
  1. Mike says:

    Franky – you need to right click ball in the Library, select properties select advanced and make sure export for runtime sharing is checked. Also make sure the Class is set to “Ball” rather than “ball”.
    or you’ll keep getting the undefined method error

    Oh – you posted in April – oh well hope someone finds it useful…

    Cheers

    Log in to Reply
  2. Franky says:

    I am getting the following error:
    1120: Access of undefined property ball
    Any ideas?

    Log in to Reply
  3. Val says:

    I loved the way you explained the lines of code. I am just starting to write the code rather than copy and paste. I thought it was interesting that your drop and drag code is different to the code I found at the flashclassroom.com
    They used
    ball_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
    ball_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);

    function pickupObject(event:MouseEvent):void {
    event.target.startDrag(true);
    }
    function dropObject(event:MouseEvent):void {
    event.target.stopDrag();
    }

    to get the same result. They suggest calling all the movie clip objects name_mc. I assume this might save confusion in more complex action scripts.

    Log in to Reply
  4. Hakan says:

    thanks for the quick reply, but it does not really help. by the way, i made all the things just using as3, as short, i have a main movieClip object and i create ball in it but as a child of stage. i’m not sure it does matter or not but if anyone can help, i’ll be appreciated. thanks in advance.

    Log in to Reply
  5. smonte says:

    Hmm I just updated the info a bit. So you need to have the registration point in the center. I think that’s causing the problem.

    Log in to Reply
  6. Hakan says:

    thanks for the code, but i think i have a scaling problem. when i do the 3rd one ball does not come under cursor, it fells middle of the its first position and mouse position. what did i make wrong?

    Log in to Reply
  7. Karlson says:

    Its realy cool ;)
    thanks

    Log in to Reply

Leave a Reply

You must be logged in to post a comment.