Dragging with trail effect

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.

Previous page

Bookmark and Share