Thursday, 20 January 2011

Multicoloured drawing in Actionscript 3

This tutorial will show you how to create a Multicoloured drawing app in Actionscript 3. The line drawings will change colour as you draw. I have used the draw application as a base for this tutorial, so the code used is similar. To achieve this effect I have stored the colours in an array and have used the Timer class to increment the array index at one second intervals when the lines are drawing.


Multicoloured drawing in Actionscript 3

Step 1

Open up a new AS3 file and set the stage size to 400 x 400. Then open up the Actions panel and enter the following code:

//Array to hold all the colours to change.
var coloursArray:Array=[0xFF0000,0xFFFF00, 0xFF7F00,0x00FF00,0x66CC66,
                        0x00F2F2,0x0000FF,0xFF00FF,0xA00172,0x000000];

//Holds the current position in the array.
var position:uint= 0;

//This creates a new instance of the Timer class with a delay of 
//1 second which will change the line colour every second. The
//repeat count is the number of the colours in the array.
var timer:Timer=new Timer(1000,coloursArray.length);
timer.addEventListener(TimerEvent.TIMER, changeColour);

//Adds a new sprite to the the stage to hold the line drawings.
var drawingLine:Sprite = new Sprite();
addChild(drawingLine);

//Adds the mouse down and mouse up listeners to the stage.
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);

//This function starts the timer and
//will show the first coloured line drawn
function mouseDownHandler(event:MouseEvent):void {
    timer.start();
    drawingLine.graphics.lineStyle(3, coloursArray[position]);
    drawingLine.graphics.moveTo(mouseX, mouseY);
    stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
}


function mouseMoveHandler(event:MouseEvent):void {
    drawingLine.graphics.lineTo(mouseX, mouseY);
}

//This function stops the timer and remove the listener from the stage.
function mouseUpHandler(event:MouseEvent):void {
    timer.stop();
    stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
}

//This function increments the position counter which will change the 
//current array index.
function changeColour(e:TimerEvent):void{
    position++;
    drawingLine.graphics.lineStyle(3, coloursArray[position]);
}

Step 2

Test your movie Ctrl + Enter. Draw some continuous lines and you will see the line change colour.



I have also added a custom cursor to my multicoloured drawing with is optional.

Alternatively, if you wish to have any number of random colours instead of ten set colours you can use the code below.
var randomColours:int = Math.random() * 0xFFFFFF;

var timer:Timer=new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, changeColour);

var drawingLine:Sprite = new Sprite();
addChildAt(drawingLine,0);

stage.addEventListener(MouseEvent.MOUSE_DOWN, MouseDown);
stage.addEventListener(MouseEvent.MOUSE_UP, MouseUp);

function MouseDown(event:MouseEvent):void {
 timer.start();
 drawingLine.graphics.lineStyle(3, randomColours);
 drawingLine.graphics.moveTo(mouseX, mouseY);
 stage.addEventListener(MouseEvent.MOUSE_MOVE, MouseMove);
}

function MouseMove(event:MouseEvent):void {
 drawingLine.graphics.lineTo(mouseX, mouseY);
}

function MouseUp(event:MouseEvent):void {
 timer.stop();
 stage.removeEventListener(MouseEvent.MOUSE_MOVE, MouseMove);
}

function changeColour(e:TimerEvent):void{
 randomColours = Math.random() * 0xFFFFFF;
 drawingLine.graphics.lineStyle(3, randomColours);
}

Saturday, 15 January 2011

Find out swf version

I found a website that provides you with the published version of the Flash player and the version of Actionscript the swf was built in. This is useful when you are given a foreign swf file and need to determine which Actionscript/Flash player version the file is created in.



All you need to do is to upload the swf file from your desktop or an online source. And the Actionscript version and Flash player version will be displayed.

Tuesday, 11 January 2011

AS3 Quotes rotator with XML

In this tutorial you will learn how to create a quotes rotator with XML using Actionscript 3. I have used quotes from famous movies in this rotator. You will need some working knowledge of XML in this tutorial. I have used the TweenNano plugin for the tweening which can be downloaded at greensock.com 


AS3 Quotes rotator with XML

Step 1


Open up your favourite text editor and add the following XML. I have used eleven quotes, but you can add in more quotes if you wish. Save the file name as: quotes.xml.

<quotes>
<quote>
<item txt="I'll be back" name="The Terminator"/>
<item txt="Goodbye, Mr. Bond" name="Goldfinger"/>
<item txt="I'll be back" name="The Terminator"/>
<item txt="Get busy livin' or get busy dyin" name="The Shawshank Redemption"/>
<item txt="Fuh-get about it!" name="Donnie Brasco"/>
<item txt="Show me the money" name="Jerry Maguire"/>
<item txt="You're gonna need a bigger boat" name="Jaws"/>
<item txt="May the force be with you" name="Star Wars"/>
<item txt="There's no place like home" name="The Wizard of Oz"/>
<item txt="Say hello to my Little Friend" name="Scarface"/>
<item txt="Houston, we have a problem" name="Apollo 13"/>
</quote>
</quotes>


Step 2

Open a new AS3 flash file and save it in the same directory as your quotes.xml file. Change the stage dimensions to 400 x 200 and choose whatever stage colour you wish. I have used #2E82FF colour for my stage colour.


Step 3


Firstly, you need to create a dynamic text field to hold the quote text. Select the text tool with dynamic text and drag out a one line text field the same width as the stage area. Change the paragraph behaviour to multiline and select the align center button. Give this text field the instance name: quote_txt. The dynamic text field will need to be converted into a movie clip so it can be animated later on. Convert the text field into a movie clip (F8) and give it the instance name: quote_mc.


Step 4

You also need a dynamic text field to hold the authors name, so repeat the same as above. Give the text field the instance name: name_txt. And the instance name: name_mc for the movie clip.

On the stage you should now have two movie clips. Inside these movie clips are two dynamic text fields.


Step 5

In the document class add the class name: RandomQuotes and then open up a new Actionscript file and enter the following code.

package {
    
    import flash.display.Loader;
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.utils.setInterval;
    
    import com.greensock.*;
        
    public class RandomQuotes extends MovieClip {
        
        private var loader:URLLoader;
        private var xml:XML;
        private var quotesArray:Array = new Array();
        private var quotesTotal:int;
        private var count:int = -1;
        
        public function RandomQuotes() {
            //Creates a new instance of the loader class to load the quotes data.
            loader = new URLLoader();
            loader.addEventListener(Event.COMPLETE, xmlLoaded);
            loader.load(new URLRequest("quotes.xml"));
        }
            
        private function xmlLoaded(e:Event):void {
                xml=new XML(e.target.data);
                addQuotes();
                setInterval(randomQuotes,6000);        
        }
        
        //Adds the quotes and authors names into the quotesArray.
        private function addQuotes():void{
            quotesTotal = xml.quote.children().length();
            
            for(var i:int = 0; i < quotesTotal; i++){
                quotesArray.push({quotes:xml.quote.children().attribute("txt")[i], 
                                  name: xml.quote.children().attribute("name")[i]})
                } 
                
            randomQuotes();    
        }
        
        
        //Displays the quotes from the xml and fades the movie clip in.
        private function randomQuotes():void{
            
            count == quotesTotal-1 ? count = 0 : count++;
            
            quote_mc.quote_txt.text =   "\"" + quotesArray[count].quotes + "\"" ; 
            name_mc.name_txt.text = quotesArray[count].name; 
            
            TweenNano.from(quote_mc, 2, { alpha:0} );
            TweenNano.from(name_mc, 2, { alpha:0} );
        }
    }
} 

Step 6

Test the movie Ctrl + Enter.



You can download the source files here.

Sunday, 9 January 2011

AS3 Bold and Italic text in dynamic text fields

Dynamic text fields in Flash CS4 don’t show Bold or Italic text for some bizarre reason. I found this out when I tried to set the character style of a dynamic text field to Italics. When I exported the movie the Italic text did not appear. I try the Bold character style and that also did not appear.

I figured out you can get around this problem by using the TextFormat class.
Here is the code I used for the Italic text.

output_txt.text='hello ilike2flash';
var ItalicText:TextFormat = new TextFormat();
ItalicText.italic=true;
output_txt.setTextFormat(ItalicText);

The code for the bold text is similar.
output_txt.text='hello ilike2flash';
var BoldText:TextFormat = new TextFormat();   
BoldText.bold=true;
output_txt.setTextFormat(BoldText);

Another solution is to use the Italic tags in the htmlText.
output_txt.htmlText = "<I>Hello</I>"
If the Bold or Italic text still does not appear in the dynamic text field. You can try embedding the fonts.

Thursday, 6 January 2011

AS3 distance between two points

I recently had to calculate the distance between two points using some simple maths. To work out the distance I used the Pythagorean Theorem (a2 + b2 = c2). I multiple the differences of the two x values and the two y values and then square root the sum of the values. Here is an example below in one line of code.

var distance = Math.sqrt( ( point1.x – point2.x ) * (point1.x - point2.x ) + (point1.y - point2.y ) * (point1.y - point2.y ));

If you want to calculate the distance between two points multiple times you can put the code into a function like below.

function DistanceTwoPoints(x1:Number, x2:Number,  y1:Number, y2:Number):
    Number {
    var dx:Number = x1-x2;
    var dy:Number = y1-y2;
    return Math.sqrt(dx * dx + dy * dy);
}

Here is an example of the distance between two points. The circle shape will be transparent when the mouse x and y positions are greater than 76 pixels and will be opaque than the mouse x and y are less than 76 pixels.

stage.addEventListener(Event.ENTER_FRAME, showDistance);

var circle:Shape = new Shape();
circle.graphics.beginFill(0x3399FF);
circle.graphics.drawEllipse(0, 0, 76, 76);
circle.graphics.endFill();
addChild(circle);

function showDistance(e:Event):void{
   var distance:Number = DistanceTwoPoints(circle.x, mouseX, circle.y, mouseY);
   trace('The distance is: ', distance);
   
   if(distance > 76){
       circle.alpha = 0
   }else{
       circle.alpha = 1;
   }
}

function DistanceTwoPoints(x1:Number, x2:Number,  y1:Number, y2:Number): Number {
    var dx:Number = x1-x2;
    var dy:Number = y1-y2;
    return Math.sqrt(dx * dx + dy * dy);
}

  COPYRIGHT © 2011 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP