Actionscript 3 Random Lines


Intro

In this tutorial, I'm going to teach you how to randomly animate lines. All this is done by using the drawing API.

Moving into Actionscript 3.0

First, let's set up the array that we use to animate the lines. Type the following.

//This array contains the current coordinates for each line.
var linesArray:Array = new Array();

//In this example, we are creating 7 lines. Change this value to whatever you want.
for (var i=0; i < 7; i++) {
	/* The array will be filled like this
	linesArray[0]: Contains line #1 x coordinate
	linesArray[1]: Contains line #1 y coordinate
	linesArray[2]: Contains line #2 x coordinate
	linesArray[3]: Contains line #2 y coordinate
	and so on ...
	We position each line to start from a random position
	*/
	linesArray.push (Math.random()*stage.stageWidth);
	linesArray.push (Math.random()*stage.stageHeight);
}

Now we are ready to animate the lines. Type the following.

//Set the line to be 2 pixels and white
graphics.lineStyle (2, 0xffffff);

addEventListener (Event.ENTER_FRAME, enterFrameHandler);

function enterFrameHandler (event:Event):void {

	//Loop through the lines' coordinates
	for (var i:uint = 0; i < linesArray.length; i+=2) {

		//Set the starting point to the current position of the line
		graphics.moveTo (linesArray[i], linesArray[i+1]);
		
		//Calcute a new random point where we want to draw
		var newX = (Math.random() * 16 - 8) + linesArray[i];
		var newY = (Math.random() * 16 - 8) + linesArray[i+1];
		
		//Draw to the new coordinates
		graphics.lineTo (newX, newY);
		
		//Set the new coordinates to be the current coordinates (we'll draw from this point in the next frame)
		linesArray[i] = newX;
		linesArray[i+1] = newY;

	}
}

That's it, test your movie! Feel free to change the values in the code and see how it looks. If you have any questions concerning the tutorials, please visit the forum.

Bookmark and Share