Sunday, 26 June 2011

Lottery app in Actionscript 3

In this tutorial you will learn how to create a Lottery application in Actionscript 3. The Lottery app will display six unique random numbers from one to forty nine. The shaking effect is created using timeline animation and the Timer class is used to stop and display the random numbers on the balls.

Lottery app in Actionscript 3

Step 1 – Create ball

Open a new Actionscript 3 Flash file with the stage dimensions 500x200. Select the Oval tool (O) and draw a oval shape on the stage with the width and height at 67.50 pixels. I have given my oval a radial gradient, but this is optional. Then convert the oval into a movie clip (F8);


Step 2 - Create ball holder

Convert the ball movie clip into another movie clip (F8). Select the 'Export for Acionscript' checkbox and give the class name: BallHolder. This will give you a movie clip inside a movie clip. Rename 'layer 1' to 'ball'. Select the timeline and Insert five key frame(F6). On the second key frame move the ball 5 pixels to right; on the third key frame move the ball 5 pixels to the left; on the fourth key frame move the ball 5 pixels upwards and finally on the fifth key frame move the ball down 5 pixels.

On the timeline insert a new layer call 'text' and select the Text tool with dynamic text and give the text field the instance name: output_txt. Embed the numerals glyphs. I have used the font Verdana with size 35pt. Now return to the main timeline and delete the ball holder movie clip from the stage. This movie clip will be added to stage dynamically so will not be needed on the stage.


Step 3 - Restart button

Select the Rectangle tool (T) and create a restart button. Convert the rectangle to a movie clip and give it the instance name: restart.


Step 4 - Add Code

Open a new AS3 class file with the name Lottery and type out the import statements and variables.

package {
 import flash.events.Event;
 import flash.filters.DropShadowFilter;
 import flash.utils.Timer;
 import flash.events.TimerEvent;
 import flash.events.MouseEvent;
 import flash.display.MovieClip;

 public class Lottery extends MovieClip {

  private var numbersArray:Array;
  private var randomArray:Array;
  private var ballsArray:Array = new Array();
  private var counter:int;
  private var numOfballs:uint = 6;
  private var timer:Timer;

  public function Lottery() {

  }
 }
}

Inside the constructor add the following code. This adds six balls on the stage with a x offset of 80 pixels. Each of the balls have a drop shadow with distance of 2 pixels, an angle of 90 degrees, black colour, blur of 5 pixels in the x and y and a strength of 80%. The ball instances get added to the ballsArray.

for (var i:uint = 0; i < numOfballs; i++) {
 var bh:BallHolder = new BallHolder();
 bh.x = 50 + (i * 80);
 bh.y = 80;
 bh.filters = [new DropShadowFilter(2,90,0,1,5,5,0.8)];
 addChild(bh);
 ballsArray.push(bh);
}

This creates a new instance of the Timer class with a delay of two seconds and a repeat counts of six. The restart button is initially hidden and the mouse click event is added to the restart button.

timer = new Timer(2000, numOfballs);
timer.addEventListener(TimerEvent.TIMER, timerHandler);

restart.visible = false;
restart.addEventListener(MouseEvent.CLICK, restartHandler);

init();

Next create an init function. This function starts with declaring two empty array and the counter at -1. To avoids any duplicate numbers I have firstly added the numbers 1-49 to the numbersArray then removed six random numbers from numbersArray. And started the timer.

private function init():void {
 numbersArray = [];
 randomArray = [];
 counter = -1;

 for (var j:uint = 1; j < 50; j++) {
  numbersArray.push(j);
 }

 for (var k:uint = 0; k < numOfballs; k++) {
    randomArray.push(numbersArray.splice(Math.floor(Math.random()*numbersArray.length), 1));
 }

 timer.start();
}

The timeHandler function increments the counter and stops each of the balls moving and also display a unique random number for each ball. When all the balls have stopped and are displaying a random number then the restart button is shown and the timer is reset.

private function timerHandler(e:TimerEvent):void {
 counter++;

 ballsArray[counter].gotoAndStop(1);
 ballsArray[counter].output_txt.text = randomArray[counter];

 if (counter == 5) {
  restart.visible = true;
  timer.reset();
 }
}

This function clears the numbers from the balls and restarts the moving animation and call the init function.

private function restartHandler(e:MouseEvent):void {
 for (var i:uint = 0; i < numOfballs; i++) {
  ballsArray[i].output_txt.text = "";
  ballsArray[i].play();
 }
 init();
}

step 5

Export the movie Ctrl + Enter.




Additional animation effects


The Lottery balls currently start shaking when the movie exports. I want the balls to drop from the top of the stage then start shaking afterwards. For the dropping effect I have used the TweenNano plugin with bounce easing which can be downloaded from greensock.com. Firsty, add the import statements.

import com.greensock.TweenNano;
import com.greensock.easing.*;


In the constructors, change the ballholders y position from 80 to -bh.height. This offsets the balls so they appear off the stage. Delete the init() function call and add the enter frame event listener.

stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);


Outside of the constructor added the following code. This function checks if the ballArray has six items before firing the TweenNano code. The check stops the animation starting before all the ballHolders have been added to ballsArray. The TweenNano code tweens the ball's y position to 80 pixels and waits two seconds to tween another ball. I have passed the target and the ii variable as the onComplete parameters.

function enterFrameHandler(e:Event):void{
 
 if(ballsArray.length == numOfballs){
  
 stage.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
  
 for(var ii:uint = 0; ii < numOfballs; ii++){
 TweenNano.to(ballsArray[ii], 1, {y:80, ease:Bounce.easeOut, delay:2 * ii, onComplete:completeHandler, onCompleteParams:[ ballsArray[ii], ii ]});
 }
  
 }
}

This function starts the balls shaking animation. The init function is fired when all the balls are shaking.

function completeHandler(mc:MovieClip, count:int):void{ 
 mc.play();
 if(count == 5) init();
}



You can download the source files here.

Friday, 24 June 2011

Animate dynamic text fields in AS3

Here is a quick example of how to animate a dynamic text field to a specific time in Actionscript 3. I will be animating the numbers from 1 – 100 in ten seconds. I have used the TweenNano class which can be downloaded from greensocks.com. To achieve this effect I have passed an object to the target of the TweenNano.to() method and assigned a target number to the startNumber property of the object. Then I use the onUpdate property to call the updateHandler function every time the tween’s time is updated. This means that every time the tween gets fired you will see the dynamic text number increase until the target number and the duration time has been reached.

import com.greensock.TweenNano;

var obj:Object = new Object();
obj.startNumber = 0;

var targetNumber:uint = 100;


TweenNano.to(obj, 10, { startNumber: targetNumber, onUpdate:updateHandler});

function updateHandler():void{
    output_txt.text = uint(obj.num).toString();
}

Wednesday, 8 June 2011

Custom Colour picker in Actionscript 3

In this tutorial you will learn how to create a custom Colour picker using only Actionscript 3 code. I have used two classes to create the color picker: Colourpick and Palette. The first class sets up the background rectangle, selector box and the text field. And the second class generates the palette of colours.


Custom Colour picker in Actionscript 3


Step 1 - embed font

Open a new AS3 file and save it with the name: Colour picker. In the library, right click on the background and select: 'New Font…' A Font embedding window should open up. Change the font family to a font of your choice I have used the Calibri font. Embed the Uppercase, and Numeral glyphs and also include a '#' character. Then in the linkage section, tick the Export to Actionscript button, leave the default Class name as: Font1 and click ok.


Step 2 - Colourpick class

Open a new AS3 class file with the name: Colourpick and firstly type out the necessary classes (import statements) and the static variables.

package {
           import flash.display.Sprite;
           import flash.events.MouseEvent;
           import flash.events.Event;
           import flash.display.Shape;
           import flash.text.*;
           import flash.display.Loader;
           import flash.net.URLRequest;

           public class Colorpick extends Sprite {
                                               
                public static var blockSelect:Sprite;
                public static var tf:TextField;
                       
                public function Colorpick() {
                       
                }

           }
}

To begin, you need to create the white rectangle box for the Colour picker’s background. I have used the drawRect() method to draw a rectangle with 90 pixels width and 20 pixels height. And use the lineStyle() method to create a 1 pixel black border around the rectangle. Now, add the code below inside the constructor.

var bg:Shape = new Shape();
bg.graphics.lineStyle(1, 0x000000);
bg.graphics.beginFill(0xFFFFFF);
bg.graphics.drawRect(0,0,90,20);
bg.graphics.endFill();
addChild(bg);           

Next you add a new instance of the Palette class. This class will be created later on. I have offset the Palette’s y position by 25 pixels, so it appears underneath the white rectangle. And set the Palette to be initially invisible.

var colourBlocks: Palette = new Palette();
colourBlocks.visible = false;
colourBlocks.y = 25;
addChild(colourBlocks);        

You now need to add a selector block which is use to show and hide the palette. I have used the first value from the coloursArray as the initial colour of the selector block.

blockSelect = new Sprite();
blockSelect.graphics.beginFill(colourBlocks.coloursArray[0]);
blockSelect.graphics.drawRect(74.25, 4, 11.55, 11.55);
blockSelect.graphics.endFill();
blockSelect.buttonMode = true;
blockSelect.addEventListener(MouseEvent.CLICK, function(){ colourBlocks.visible = !colourBlocks.visible; });
addChild(blockSelect);

I have added the selector block’s outline separately to prevent it from disappearing when you mouse over a different colour from the palette.

var outline:Shape = new Shape();
outline.graphics.lineStyle(1, 0x000000);
outline.graphics.drawRect(74.25, 4, 11.55, 11.55);
outline.graphics.endFill();
addChild(outline);

Finally, you need to add the text box. I have used the TextFormat and TextField classes to create a dynamic text field. The dynamic text uses the same font from the library. You may need to adjust the x and y positions and the font size if you are using a different font to the one I’m using. I have set the default text to show the initial block selector colour which is: #8B8989.

var format:TextFormat = new TextFormat();
var myFont:Font = new Font1();
format.size = 15;
format.font = myFont.fontName;
                                  
tf = new TextField();
tf.width = 69.50;
tf.height = 22;
tf.x = 6;
tf.y = -1;
tf.type = TextFieldType.DYNAMIC;
tf.defaultTextFormat = format;
tf.embedFonts = true;
tf.text = "#"+colourBlocks.coloursArray[0].toString(16).toUpperCase();
addChild(tf)

Step 3- Pallete class

Open a new AS3 class file with the name: Palette and type out the necessary classes and variables. You can change the values in the colourArray to change the colours in the palette.

package  {
 
 import flash.display.Sprite;
 import flash.geom.Rectangle;
 import flash.events.MouseEvent;
 import flash.filters.GlowFilter;
 import flash.display.BitmapData;
 import flash.geom.ColorTransform;
 import flash.system.*;
 
 public class Pallete extends Sprite {
  
  private var cols:uint = 8;
  private var xOffset:Number = 11.8;
  private var yOffset:Number = 12;
  
  public var coloursArray:Array = new Array(
  0x8b8989,0x191970,0x2e8b57,0xcd5c5c,0x00FF33,0xFFFF00,0xFF3399,0x3333CC,
  0x80FF02,0x7b68ee,0x2e8b57,0x8b4513,0xCC0000,0xFFFF66,0x660099,0x330066,
  0xffdead,0x7b68ee,0x2e8b57,0xf4a460,0xCC3300,0xFFCC99,0x33FFCC,0x0066CC,
  0x708090,0x0000ff,0x2e8b57,0xb22222,0xFF3300,0xFF3399,0x33CCFF,0x0000CC);
  
  private var bpdata:BitmapData;
  private var autoHide:Boolean = true;
 
  public function Pallete() {
     
  }
 }
}

Inside the constructor add the code below. The For loop creates all the colour blocks using the colours from the coloursArray with the size 9.85 width and 9.80 height. Also adds a black outline and the mouse out, over, mouse and click listeners. The colour blocks will appear as eight columns by for four rows.

for(var i:uint = 0; i < coloursArray.length; i++){
                                              
var s:Sprite = new Sprite();
s.graphics.lineStyle(0.1,0x000000);
s.graphics.beginFill(coloursArray[i]);
s.graphics.drawRect(0,0, 9.85, 9.80);
s.graphics.endFill();       
s.x = 0 + xOffset * (i%cols);
s.y = 0 + yOffset * int(i/cols);         
s.addEventListener(MouseEvent.MOUSE_OUT, outHandler);
s.addEventListener(MouseEvent.MOUSE_OVER, overHandler);              
s.addEventListener(MouseEvent.MOUSE_MOVE, moveHandler);
s.addEventListener(MouseEvent.CLICK, clickHandler);                                              
addChild(s);
}
}
Next create a new instance of the BitmapData class. This is used to get the pixel data from the colour blocks.

bpdata = new BitmapData(width, height);
bpdata.draw(this);

To hide the palette when you mouse out of the colour blocks. I have created roll areas to set the palette invisible when these areas get moused over.

if(autoHide){
var bounds:Rectangle = getBounds(this);
var offset:uint = 10;
                                  
var rollArea:Sprite = new Sprite();
rollArea.graphics.beginFill(0x000000, 0);                        
rollArea.graphics.drawRect(-bounds.width-offset,0, bounds.width, bounds.height);
rollArea.graphics.drawRect(bounds.width+ offset,0, bounds.width, bounds.height);
rollArea.graphics.drawRect(-bounds.width, bounds.height+10, bounds.width*3, bounds.height);
rollArea.graphics.endFill();
rollArea.addEventListener(MouseEvent.MOUSE_OVER, function() { visible = false; } );
addChild(rollArea);
}

These functions gives the blocks a subtle glow effect when you mouse over the blocks and removes the glow effect when the mouse is off the blocks.

private function overHandler(e:MouseEvent):void{
e.currentTarget.filters = [new GlowFilter(0xFFFFFF,1,5,5,1,3,true)];
}
                      
private function outHandler(e:MouseEvent):void{
           e.currentTarget.filters = null;
}

This function changes the colours of the block selector and updates the colour value in the text field.


private function moveHandler(e:MouseEvent):void{
 var selectedColour:uint = bpdata.getPixel(mouseX, mouseY);
                                  
 var colourtransform:ColorTransform = new ColorTransform();
 colourtransform.color = selectedColour;
                                  
 //hides black colour
if(selectedColour != 0){                                            
Colorpick.blockSelect.transform.colorTransform = colourtransform ;
Colorpick.tf.text = "#"+selectedColour.toString(16).toUpperCase();
}
}

This function hides the palette when you click on a block, and also saves the colour value to the clipboard.

private function clickHandler(e:MouseEvent):void{
           visible = !visible;
           System.setClipboard(Colorpick.tf.text);
}

Step 4 – Test the movie

To test the movie you would add the code below.

var cp: Colorpick = new Colorpick();
addChild(cp);

Tuesday, 7 June 2011

Drop image using XML in AS3

In this tutorial you will learn how to create a drop image effect using XML in Actionscript 3. The drop image effect will dynamically load images which will get dropped from the top of the stage. You will need some images for this tutorial. The images will get resized using code, so the dimensions aren’t that important, obviously the smaller the size the faster it will take to load. The greensock plugin is also needed which can be downloaded from greensock.com


Drop image using XML in AS3

Step 1

Open up any text editor and type out the following XML and save the file with the name: ‘DropImages.xml’. I have put my images in a folder called ‘images’ and have used six images. You can use as many images as you wish.

<images>
<image src="images/picture1.jpg" />
<image src="images/picture2.jpg" />
<image src="images/picture3.jpg" />
<image src="images/picture4.jpg" />
<image src="images/picture5.jpg" />
<image src="images/picture6.jpg"/>
</images>


Step2

Open a new AS3 document and save it with the name: DropImage. I have used the stage dimensions 400x400 for my FLA. Then open up a new AS3 class file with the name: DropImage and set this as the document class then type out the following code:

package {

 import flash.display.MovieClip;
 import flash.events.Event;
 import flash.net.URLLoader;
 import flash.net.URLRequest;
 import com.greensock.TweenNano;
 import com.greensock.easing.*;

 public class DropImage extends MovieClip {

  private var containerArray:Array = new Array  ;
  private var totalImgs:int = -1;
  private var counter:uint = 0;
  private var imageLength:uint;

  public function DropImage() {
   //Loads the xml
   var xmlLoader:URLLoader = new URLLoader  ;
   xmlLoader.load(new URLRequest("DropImages.xml"));
   xmlLoader.addEventListener(Event.COMPLETE,xmlLoaded);
  }

  //Creates new instances of the ImageContainer class with the y position
  //initally set off the stage and the rotation at -90. The -90 rotation
  //gives the dropping effect as the object gets tweened downwards.
  private function xmlLoaded(e:Event):void {
   var xml:XML = new XML(e.target.data);

   imageLength = xml.image.length();

   for (var i:int = 0; i < xml.image.length(); i++) {
    var imgc:ImageContainer = new ImageContainer(xml.image[i].attribute("src"));
    imgc.x = 100;
    imgc.y = -133;
    imgc.rotation = -90;
    imgc.alpha = 0;
    imgc.addEventListener("imageloaded",showImage);
    addChild(imgc);
    containerArray.push(imgc);
   }
  }


  //waits for all images before tweening
  private function showImage(e:Event):void {
   totalImgs++;
   if (totalImgs == imageLength - 1) {
    tweenBox();
   }
  }


  //tweens the images downwards to a randoms rotation between -11 and 11
  //and replays the tween after two seconds.
   private function tweenBox():void {
    
    TweenNano.to(containerArray[counter],1, {y:192.45,
         rotation:Math.floor(Math.random() * 11) - 11,
         alpha:1,
         ease:Sine.easeOut,
         onComplete:function(){
        if(counter != containerArray.length - 1){
         counter++;   
         TweenNano.delayedCall(2, tweenBox);
       }
         }});
  }
 }
}


Step 3

Open up a new AS3 class file and save it with the name: ImageContainier then type out of the following code below. The ImageContainer class is used to create the white background border using the AS3 graphics api. And load the images dynamically using the Loader class. The loaded image gets resized as a bitmap by setting the width and height to 90% of the white backgrounds width and height.  A new event is dispatched once the image is loaded. This is to check for all images have been loaded being starting the tween animation. 

package {
 import flash.display.Sprite;
 import flash.display.Bitmap;
 import flash.display.Loader;
 import flash.display.Shape;
 import flash.events.Event;
 import flash.net.URLRequest;
 import flash.filters.DropShadowFilter;

 public class ImageContainer extends Sprite {

  private var bgWidth:Number = 210;
  private var bgHeight:Number = 130;
  //resize image will be 90% of the background.
  private var resizeWidth:Number = 210 * 0.9;
  private var resizeHeight:Number = 130 * 0.9;
  private var resizeXOffset:Number = 10;
  private var resizeYOffset:Number = 6;


  public function ImageContainer(_imageName) {
   //Add white background border with a dropshadow.
   var bg:Shape = new Shape  ;
   bg.graphics.beginFill(0xffffff);
   bg.graphics.drawRect(0,0,bgWidth,bgHeight);
   bg.graphics.endFill();
   bg.filters = [new DropShadowFilter(3,45,0x000000,1,5,5,0.9,3)];
   addChild(bg);

   //Loads image
   var loader:Loader = new Loader();
   loader.contentLoaderInfo.addEventListener(Event.COMPLETE,showImage);
   loader.load(new URLRequest(_imageName));
  }


  private function showImage(e:Event):void {
   //resizes the loaded image
   var bp:Bitmap = Bitmap(e.target.content);
   bp.smoothing = true;
   bp.width = resizeWidth;
   bp.height = resizeHeight;
   bp.x = resizeXOffset;
   bp.y = resizeYOffset;
   addChild(bp);
   dispatchEvent(new Event("imageloaded"));
  }
 }
}


Step 4

Export the movie Ctrl + Enter. You should now have a drop image effect in Actionscript 3.

Sunday, 5 June 2011

External wav files in Actionscript 3

In Actionscript 3 you can only play wav files that are imported into the Flash library you can’t play external wav files. This is because when wav files are in the library they get converted in Sound objects which give support for playing the wav file format. The external wav format is not natively supported in the Sound Class.

However, there is a class called: as3wavsound which can be downloaded here. The as3wavsound class has essentially the exact same API as the native Sound class apart from the ability to play wav files. This makes it simple and easy to use, here is an example.

var loader:URLLoader = new URLLoader();
loader.dataFormat = 'binary';
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.load(new URLRequest("[yourwavfile].wav"));


function completeHandler(e:Event):void{
 var sound:WavSound = new WavSound(e.target.data as ByteArray);
 sound.play();
}

  COPYRIGHT © 2011 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP