Monday, 12 April 2010

Timed random rectangles in AS3

In this tutorial you will learn how to create randomly coloured and sized rectangles on the stage at timed internals. To achieve this effect I have used the timer class to set a timer delay of 500 milliseconds which will trigger a function to create rectangles on the stage. The rectangles are created using the drawRect() method from the Graphics class.

Timed random rectangles in Actionscript 3

Step 1

Open a new Flash AS3 file then open up the Actions panel and enter the following code.

//This creates a new instance of the timer class with a delay of 500 milliseconds.
var myTimer:Timer=new Timer(500);

//Adds an event listener to the timer which will trigger the randomCircles function
//every 500 milliseconds.
myTimer.addEventListener(TimerEvent.TIMER, randomCircles);

//Starts the timer.

function randomCircles(event:TimerEvent):void {
//The randomColour variable will give a random colour.
var randomColour:int = Math.floor(Math.random() * 0xFFFFFF);

//The randomSize will give a random size between 10 - 100.
var randomSize:int = Math.floor(Math.random() * 100) +10;

//This creates a new instance of the shape class with
//random colour and size.
var myRect:Shape = new Shape();, 1);,0, randomSize, randomSize);;

//This places the rectangle on the random position on the stage.
myRect.x = Math.floor(Math.random() * stage.stageWidth);
myRect.y = Math.floor(Math.random() * stage.stageHeight);

//Add the rectangle on the stage.

Step 2

Test your movie Ctrl + Enter.


  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP