ActionScript 3 Dragging Methods

February 6, 2009 by: smonte

In the last part of this tutorial, I will teach you how to create a trail effect while dragging an object.

1. Linkage the ball movie clip to a class named “Ball”. If you don’t know how linkage a movie clip, check step 4 of the ActionScript 3 External Classes tutorial.

2. Add the following code in your ActionScript code (don’t erase the old one).

 
//We use this timer to create a trail ball each 0.03 seconds
var timer:Timer = new Timer(30,400000);
timer.addEventListener(TimerEvent.TIMER, createTrailBall);
timer.start();
 
//This function is called by the timer
function createTrailBall(e:Event):void {
 
        //Create a new ball instance
        var trailBall:Ball=new Ball();
 
        //Position the trail ball in the same position where the original ball is located
        trailBall.x = ball.x;
        trailBall.y = ball.y;
 
        //Add ENTER_FRAME to animate the trail ball
        trailBall.addEventListener(Event.ENTER_FRAME,animateTrailBall);
 
        /* Add the trail ball on to the stage. We don't want to position the trail ball on top of the original ball. We use the addChildAt method to set the index to 0. */
        addChildAt(trailBall,0);
}
 
function animateTrailBall(e:Event):void {
 
        //In each frame, reduce the alpha and the scale of the trail ball.
        e.target.alpha -= 0.1;
        e.target.scaleY -= 0.1;
        e.target.scaleX -= 0.1;
 
        /* If the alpha is less than 0, we remove the trail ball from the stage. */
        if (e.target.alpha < 0) {
                e.target.removeEventListener(Event.ENTER_FRAME,animateTrailBall);
                removeChild((MovieClip)(e.target));
        }
}

That’s it for this tutorial. I hope you enjoyed it and learned something new! Remember, if you have any questions, post them in the forum.

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

Comments

4 Responses to “ActionScript 3 Dragging Methods”
  1. 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.

    Reply
  2. 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.

    Reply
  3. 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?

    Reply
  4. Karlson says:

    Its realy cool ;)
    thanks

    Reply