Sunday, 20 March 2011

TimelineLite in Actionscript 3

TimeLinelite is a library from the author of TweenLite that allows you to group instances of TweenLites together to form a sort of coded timeline movie clip container. TimeLinelite gives you more power and control over the functionalities of your tweens.

Here are some of my examples. The first example uses the append() method which adds the TweenLite instances to the end of the timeline. The code below will move the mc1, mc2 and mc3 movieclip’s x position 100 pixel, one after the other.

var timeline:TimelineLite = new TimelineLite();
timeline.append( new TweenLite(mc1, 0.5, {x:100}) ); 
timeline.append( new TweenLite(mc2, 0.5, {x:100}) ); 
timeline.append( new TweenLite(mc3, 0.5, {x:100}) );

The append() method has an optional offset parameter which will offset the insertion point of a tween. This parameter can be a positive or a negative number. A positive number will cause a delay before the tween is inserted, and a negative number will overlap the previous tween. The code below will create a 1 second delay for the second and third tween. If you change the 1 for a -1 it will overlap the first tween.

var timeline:TimelineLite = new TimelineLite();
timeline.append( TweenLite.to(mc1, 0.5, {x:100}) ); 
timeline.append( TweenLite.to(mc2, 0.5, {x:100}), 1 ); 
timeline.append( TweenLite.to(mc3, 0.5, {x:100}), 1 );

The second example uses the insert() method. This method inserts a Tweenlite instance into the timeline at a specific time or label.

var timeline:TimelineLite = new TimelineLite();
timeline.insert( TweenLite.to(mc1, 0.5, {alpha:0}), 1.5); 
timeline.insert( TweenLite.to(mc2, 5, {y:100}) , 0 ); 
timeline.insert( TweenLite.to(mc3, 0.5, {x:100}),0.5);

The code above starts by tweening mc2’s y position 100 pixels, then mc3’s x position 100 pixels and finally mc’s alpha property to 0. The third example uses the prepend() method to add a Tweenlite instance at the beginning of the timeline.

var timeline:TimelineLite = new TimelineLite();
timeline.insert( TweenLite.to(mc1, 0.5, {alpha:0}), 1.5); 
timeline.insert( TweenLite.to(mc2, 0.5, {y:100}) , 0 ); 
timeline.insert( TweenLite.to(mc3, 0.5, {x:100}),0.5);

timeline.prepend( TweenLite.from(mc4, 1, {alpha:0}) );

There is also the appendMultiple(), prependMultiple(), and insertMultiple() methods which allow you to append, prepend and insert multiple Tweens at once. The fourth example controls the playback of the timeline using the play() and reverse() methods. The other playback methods include: pause(), resume() and restart().



var mcArray:Array = new Array();
var timeline:TimelineLite = new TimelineLite({onComplete:completeHandler});

for(var i:uint = 0; i < 30; i++){
 var mc:Mc = new Mc();
 mc.x = stage.stageWidth/2 - mc.width/2;
 mc.y = stage.stageHeight - mc.height;
 container.addChildAt(mc,0);
 mcArray.push(mc);
 
 var r:Number =Math.random();
 timeline.append(TweenLite.to(mcArray[i], 1, {y:0,
     x:Math.random() * stage.stageWidth,
     rotation:Math.random() * 30 + 10,
     scaleX: r,  scaleY: r,
     alpha: 0.3 + Math.random() * 0.8
     }),-0.8);
}


function completeHandler():void{
 TweenLite.delayedCall(1, function(){ timeline.reverse();  });    
}  

The overall speed of timeline can be changed using the timescale property. The default value is 1. The speed can be doubled if the timescale is set to 2, and can be halved if the timescale is set to 0.5. It is also possible to scrub through the timeline with a slider by using the currentProgress property of the timeline.

Saturday, 19 March 2011

Simple shooting game in AS3

In this tutorial you will learn how to create a simple shooting game in Actionscript 3. The objective of the game is to shoot the moving target on the screen. You have three tries to shoot the targets. If you manage to shot three targets without missing them, you win the game. Otherwise you lose the game. I have a used a free stock image of a bottle for the moving targets, but an image will work.


Simple shooting game in AS3


Step 1

Open a new AS3 file with the stage dimensions 500 x 120 and import an image on the stage by pressing File > Import > Import to stage. I have used an image of a beer bottle, but you can use any image. Convert the image into a movie clip (F8) and check the ‘Export for Actionscript’ button and give the identifier: Bottle. Once you have created the movie clip delete it from the stage.


Step 2

On the menu bar select Insert > New symbol select the type movie clip and give the name: shots and check the Export for Actionscript and give the identifier: Shots then click ok. In this movie clip you will create the bullets for the game, so in the first frame create three bullets. You can either create the bullets using the shape tools or import an image of a bullet. Then in the second frame remove one of the bullets. Again in the third frame remove another bullet. And finally in the fourth frame remove the last bullet. Insert a new layer on timeline call Actions and then open the Actions panel and add a stop() method. Now return to the main timeline.



Step 3

Again on the menu bar select Insert > New symbol select the type movie clip and give the name: endBox and check the Export for Actionscript and give the identifier: EndBox. This movie clip will display a message if you have won or lost the game. In the first frame create a rectangle shape with the text ‘You win’. And in the second frame create a rectangle shape with text ‘You lose’. Insert a new layer call Actions and then open the Actions panel and add a stop() method. Now return to the main timeline.


Step 4

Open a new Actionscript 3 class file and save it with the name: Shoot. Then add the following code below. Make sure you add ‘Shoot’ to the document class.
package{
 
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;

public class Shoot extends MovieClip {

private var bottleArray:Array = new Array();
private var numOfBottle:uint = 9;
private var bottleHit:uint = 0;
private var hits:uint = 6;
private var bottle:Bottle;
private var shots:Shots;
private var endBox:EndBox;
private var bg:Sprite;

 
public function Shoot() {
   
   stage.addEventListener(Event.ENTER_FRAME, enterHandler);
   
   //Adds the bottles onto the stage.
   for (var i:int = 0; i < numOfBottle; i++) {
    bottle = new Bottle();
    bottle.x = 0 + (i * 60);
    bottle.y = 14.35;
    bottle.addEventListener(MouseEvent.CLICK, clickHandler);
    addChild(bottle);
    bottleArray.push(bottle);
   }
   
   //Adds a invisibe background to detect when the targets have been missed.
   bg = new Sprite();
   bg.graphics.beginFill(0x000000,0);
   bg.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
   bg.graphics.endFill();
   addChildAt(bg,0);
   bg.addEventListener(MouseEvent.CLICK, checkShots);
   
   //Adds the number shot left to stage. 
   shots = new Shots();
   shots.x = 434.85;
   shots.y = 95.75;
   addChild(shots);
   
   endBox = new EndBox();
   addChild(endBox);
   endBox.x = 148;
   endBox.y = 32;
   endBox.visible = false;
   
  }
  
  
  //This function moves the all the bottles in the array four pixels to the 
  //right at the current frame rate. If a bottle goes passed the stage 
  //width, it will get re-added a bottle width before the start of the stage.
  private function enterHandler(e:Event):void{
   for (var j:uint = 0; j <  bottleArray.length; j++) {
    bottleArray[j].x +=  1;

    if (bottleArray[j].x > stage.stageWidth + bottleArray[j].width) {
     bottleArray[j].x = 0 - bottleArray[j].width;
    }
   }
  }
  
  
  //This removes the bottle from the stage, the event listener and 
  //removes it from the array if it has been clicked. 
  private function clickHandler(e:MouseEvent):void {
   var index:uint = bottleArray.indexOf(e.currentTarget);
   var target:MovieClip = e.currentTarget as MovieClip;

   target.removeEventListener(MouseEvent.CLICK, clickHandler);
   removeChild(target);
   bottleArray.splice(index, 1);

   checkShots();
  }
  
  
  private function checkShots(e:MouseEvent = null):void{
   //This increments the bottleHit counter by one and goes to 
   //the next frame in shots movie clip.
   bottleHit++;
   shots.gotoAndStop(shots.currentFrame + 1);

  
   //If there are no more shot available and array length is six then you win. 
   if (shots.currentFrame == shots.totalFrames && bottleArray.length == hits) {
    removeObject();
    endBox.visible = true;
    endBox.gotoAndStop(1);
   }
   //If there are no more shot available you lose.
   else if (shots.currentFrame == shots.totalFrames) {
    removeObject();
    endBox.visible = true;
    endBox.gotoAndStop(2);
   }
  }
  
  //This removes the event listeners
  private function removeObject():void{
   stage.removeEventListener(Event.ENTER_FRAME, enterHandler);
   bg.removeEventListener(MouseEvent.CLICK, checkShots);

   for (var i:int = 0; i < bottleArray.length; i++){
    bottleArray[i].removeEventListener(MouseEvent.CLICK, clickHandler);
   }
  }
 }
}



Step 5

Test your movie Ctrl + Enter



You can download the source files here.

Sunday, 6 March 2011

Custom drawing app in Actionscript 3

This post is an alternative to the drawing lines tutorials where I will use the primitive shapes from Flash to create the colour and size palettes instead of using the default colour picker.


Custom drawing app in Actionscript 3

Step 1


Open up a new AS3 file and select the Oval tool and draw six oval shapes on the stage. My ovals are 25x25 in size and have a 2pt black stroke. Once you have created all the shapes selected them all and convert them into a single movie clip with the instance name: coloursBlock


Step 2


Repeat the same for the size palettes, but this time use a black colour fill for the three shapes and use the text tool to type: S, M and L respectively on the shapes. Convert each of the shapes into movie clips and give them the instance names: smallSize, mediumSize and largeSize.


Step 3   

Select the Rectangle tool with a white colour fill and draw a shape to fill the stage area. Ensure you do not cover up the palettes. Covert the shape into a movie clip with the instance: drawArea


Step 4

On the timeline create a new layer called Actions then open up the Actions panel and enter the following code:

 //Variables for storing the size and colour of the drawings.
var selectedColour:uint = 0x000000;
var selectedSize:uint = 3;

//This creates a new sprite and add it to the draw area.
var drawingLine:Sprite = new Sprite();
drawArea.addChild(drawingLine);

//This creates a new instance of the BitmapData class with the
//width and height of the movie clip image.
var bmpData:BitmapData = new BitmapData(coloursBlock.width, coloursBlock.height);
bmpData.draw(coloursBlock);

//Adds listeners. 
stage.addEventListener(MouseEvent.MOUSE_DOWN, MouseDown);
stage.addEventListener(MouseEvent.MOUSE_UP, MouseUp);
smallSize.addEventListener(MouseEvent.CLICK, sizeHandler);
mediumSize.addEventListener(MouseEvent.CLICK, sizeHandler);
largeSize.addEventListener(MouseEvent.CLICK, sizeHandler);
coloursBlock.addEventListener(MouseEvent.CLICK, colourClick);

//This function draws the lines when the mouse is pressed. 
function MouseDown(event:MouseEvent):void{
    drawingLine.graphics.lineStyle(selectedSize,selectedColour);
    drawingLine.graphics.moveTo(mouseX, mouseY);
    drawArea.addEventListener(MouseEvent.MOUSE_MOVE, MouseMove);
}

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

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

//This function sets the size of the lines. 
function sizeHandler(e:MouseEvent):void{
    switch(e.target){
        case smallSize:  selectedSize  = 3; break;
        case mediumSize: selectedSize  = 6; break;
        case largeSize:  selectedSize  = 9; break;
    }
}

//This function sets the colour of the line by getting the colours
//from the block of colours.
function colourClick(e:MouseEvent):void{
    selectedColour = bmpData.getPixel(coloursBlock.mouseX, coloursBlock.mouseY);
}

Step 5

Test your movie Ctrl + Enter.

Wednesday, 2 March 2011

AS3 colour picker tool

In this tutorial you will learn how to create a custom colour picker tool in Actionscript 3. The tool will display the sample colour from an image and also display the hexidecial value of the colour. For this tutorial you will need any image.


AS3 colour picker tool


Step 1

Open up a new AS3 file and import your image onto the stage by selecting File > Import > Import to stage. Convert your image into a movie clip (F8) and give it the instance name: image_mc.



Step 2

Next you need to create a dynamic text field on the stage with the Text tool and give it the instance name: output_txt. This text field will display the hexadecimal representation of the sampled colour.


Step 3

Select the rectangle tool with black colour fill and make a small rectangle shape on the stage. Then convert your shape into a movie clip (F8) and give it the instance name: colourBlock_mc. This block will show the colour of the current sampled area.


Step 4

On the timeline insert a new layer called Actions then open up the Actions panel (F9) and enter the following code.

//This creates a new instance of the BitmapData class with the
//width and height of the movie clip image.
var imageBitmap:BitmapData = new BitmapData(image_mc.width, image_mc.height);

//This draws the image onto the bitmapdata.
imageBitmap.draw(image_mc);

//Adds the mouse move event onto the stage.
stage.addEventListener(MouseEvent.MOUSE_MOVE, detectColour);


function detectColour(event:MouseEvent):void{

//The pixel values of the mouse x and y position
//of the bitmap is stored in a variable.
var dColour = imageBitmap.getPixel(mouseX, mouseY);

//The ColorTransform class changes the colour of the rectangle 
//to the colour at the mouse postion. 
var cTrans:ColorTransform = new ColorTransform();
cTrans.color = dColour;
colour_mc.transform.colorTransform = cTrans ;


//Display in hexidecial represenation with all uppercase characters.
output_txt.text = "0x"+dColour.toString(16);
}


Step 5

Test your movie Ctrl + Enter.



Now move your mouse cursor around the image and you should see the rectangle shape and the text field change values.

  COPYRIGHT © 2011 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP