RSS twitter

Posts tagged ‘actionscript 3 basics’

Basics of ActionScript

Introduction to ActionScript 3

What is ActionScript?

ActionScript is automatically included in the Flash CS3, so you don’t need to do any additional installs. Basically, ActionScript enables you to develop interactive Flash applications. Allthough ou can build some kind of interactivity without writing any code, I strongly suggest that you make an effort and learn ActionScript. It pays off at the end. My tutorials will focus on ActionScript 3.0, which is the newest version of ActionScript. I’m not going to cover the differences between the old and the new versions, since there are many sites about that already.

Your first ActionScript application

Now we’re ready to build our first Flash application with ActionScript. To start off, follow these simple steps.

1. Create a new document (Flash File ActionScript 3.0)

2. Create a new layer, name it ”ActionScript”.

3. In the ”ActionScript” layer, select the first frame.

It is always a good practice to create a new layer for ActionScript. Although you can insert code into any layer, it keeps you more organized to have all your ActionScript in one layer.

4. Type the following code in the actions panel. If you don’t see the panel, press F9 (Window -> Actions).

trace("Welcome to learn ActionScript");

Note that a small ”a” symbol appears in the frame where you inserted ActionScript code.

5. Test the movie (Ctrl + Enter). You should see the same as below:

That’s how easy it is to insert ActionScript into your Flash application. I admit it, this application doesn’t do much, but as we go on, you’ll start to see the real power behind ActionScript.

Adding movie clips to our application

Next, we create two movie clips into our application, which we manipulate by using actionsctipt.

1. Create a new layer called ”ball”. Draw a ball in that layer and convert it into a movie clip. You can name it anyway you want.

2. Create a new layer called ”rectangle”. Draw a rectangle and convert it into a movie clip. You can name it anyway you want.

3. Select the ball. Give it an instance name ”myFirstBall”.

We give our movie clips instance names, so we can access them by using ActionScript.

4. Select the rectangle. Give it an instance name ”myFirstRectangle”.

5. Open the actions panel and write the following.

myFirstBall.alpha = 0.2;
myFirstRectangle.scaleY = 2;

6. Test your movie.

You should see that the ball’s alpha has reduced and it’s more transparent. The rectangle has stretched in vertical direction. All this happened, because we changed their properties by using ActionScript. These changes only apply to these two instances. If you were to drag a new rectangle to the stage, it’s going to look normal, since we haven’t used any actionsctipt for that particlar rectangle.

In this example, I only modified the alpha and scaleY properties, but you can manipulate all the object’s properties. For a list of the properties, refer to Adobe’s documentation.

Using functions

We already have used one function in this tutorial, the trace() function. It is a function that prints into the Flash output window. In our case, we gave it a parameter called ”Welcome to learn ActionScript”. We are not bound to use only the functions that Flash provides. We can also create our own functions. This lesson is all about creating and using functions. You can continue using the same flash file as earlier..

1. In the actions panel, type

var firstNumber:Number = 3;
var secondNumber:Number = 5;

Explanation:

The ”var” stands for variable. Everytime you create a new variable, you start the name with a ”var” statement. After the ”var”, you give your variable a name. This is the same as giving instance names (as we did earlier with the ball and the rectangle).

The ”Number” tells that the variable is a number. There are many different types of variables that you’ll learn by following my tutorials. After the name and type declaration, we assingn a value to a variable.

2. Add the following code (after the variable declarations).

function addNumbers(first:Number, second:Number):void  {
	var result:Number = first + second;
	trace("Result is " + result);
}

Explanation:

Functions always start with the word ”function”. After that, you give it a name. Our function is called ” addNumbers”. The function simply adds two numbers.

The function takes two parameters. These parameters are called ”first” and ”second”. These parameters can only be used inside of the function. You don’t need a ”var” statement with function parameters.

The ”:void” tells that this function isn’t going to return any value. We’ll learn more about this later, so don’t worry about it now.

In the function ”addNumbers”, we simply add two numbers that were sent into the function. We use the ”trace” function to print the result.

3. Insert the function call.

addNumbers(firstNumber, secondNumber);

Explanation:

This line calls our function. Without this line, the result wouldn’t be displayed in the output window, since nothing would call the “addNumbers” function!

4. Test your movie.

Final Code

trace("Welcome to learn ActionScript");

myFirstBall.alpha = 0.2;
myFirstRectangle.scaleY = 2;

var firstNumber:Number = 3;

var secondNumber:Number = 5;

//This function adds two numbers
function addNumbers(first:Number, second:Number):void  {

	var result:Number = first + second;
	trace("Result is " + result);
}

addNumbers(firstNumber, secondNumber);

Create Basic Flash Preloader

In this tutorial, I’m going to show you how to build a preloader. You should have your own preloader in minutes!

  1. Create a new document.
  2. Name the first layer to “loader bar”
  3. Draw a line. This line will be our preloader bar.
  4. Convert the line into a movie clip. Set the registration point to the top left corner.
  5. Give the line an instance name of “preloaderBar”.
  6. Create a new layer called “actions”
  7. Type the following in the “actions” layer
preloaderBar.scaleX = 0;
var loader = new Loader();
loader.load(new URLRequest("main.swf"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
addChild(loader);

Explanation: First we set our preloader’s X scale to zero. This way, the user can’t see the preloader at the beginning of the loading process. Then, we create a Loader object. The Loader object is used to load SWF files or image files. After the Loader is created, we tell it load our main movie (main.swf). Then comes the important part, we assign event handlers for the loader. To be more specific, we are using the “contentLoaderInfo” to access loading progress information and statistics. In this case, we want to know when the loading is still in progress (progressHandler) and when the loading is complete (onCompleteHandler). Last, we add the loader to the stage.

NOTE: You must have the “main.swf” file in the same directory as this loader file!

8. Now that we have our loader ready, we can write the functions that are responsible for animating the preloader. Type the following

function onCompleteHandler(e:Event):void {
	preloaderBar.visible = false;
}
function progressHandler(e:ProgressEvent):void {
	var per = e.bytesLoaded/e.bytesTotal;
	preloaderBar.scaleX = per;
	loader.visible = true;
}

Explanation: The “onCompleteHandler” is called when the loading is done. In this case, we don’t want to show the user our preloader anymore, so we make it invisible. The “progressHandler” is called everytime the loading progresses. Here, we simply calculate the percentage that has been loaded (loaded/total size). Then, we assign into the preloader’s X scale property the precentage value. So when the percentage is 1 (loading is done), the “preloaderBar” will be at full width (scaleX = 1).

9. Test your movie!

NOTE: You can simulate a download in the Flash IDE. Test your movie and go to View-> Simulate Download.

How to Create ActionScript 3.0 Events

In order to create an interactive Flash application, we need to learn something about events. An event is something that just happens in the application. There are many different types of events, such as mouse clicks, mouse move and mouse out. In this tutorial, you’ll learn how to respond to such events.

Note: You should already be familiar with the basics of flash

Handling mouse clicks

To create a movie clip that responds to mouse clicks, follow these steps.

1. Draw a rectangle and convert it into a movie clip (press F8).

2. Give the rectangle an instance name of ”myRectangle”.

3. Create a new layer called ”actions”.

4. Type the following code in the actions panel (press F9 if you can’t see the panel)

function rectangleClicked(evt:Event):void {
	myRectangle.alpha = 0.2;
}

Explanation: The function parameter is an event type. We call it ”evt” in our function. We’ll cover the Event type a little later. For now, just remember that you need to give an event handler an event parameter. Once the user clicks the button, the rectangle’s alpha is going to change.

5. So how do we know when the rectangle is clicked? For this , we use the ”addEventListener” method. Type the following.

myRectangle.addEventListener(MouseEvent.CLICK, rectangleClicked);

Explanation: The ”addEventListener” adds a listener to the rectangle. The first parameter describes which event we are listening. We use ”MouseEvent.CLICK”, because we want to know when the user clicks the rectangle. The second parameter defines which function we call, when the user clicks the rectangle.

6. Test your movie!

Handling mouse hovers

If you want the object to respond on a mouse hover, you only need to change some parts of the code. Here is the code for mouse hover.

function rectangleOver(evt:Event):void {
	myRectangle.alpha = 0.5;
}

myRectangle.addEventListener(MouseEvent.MOUSE_OVER, rectangleOver);

Explanation: This time we want to listen for a “MOUSE_OVER” event. We added another event listener to the rectangle for this.

Handling mouse out

If you want the object to react when you move your mouse out of the rectangle, you apply the following code (don’t delete the old functions).

function rectangleOut(evt:Event):void {
	myRectangle.alpha = 1;
}
 
myRectangle.addEventListener(MouseEvent.MOUSE_OUT, rectangleOut);

Now we have an interactive rectangle! You could use this in your website for example as a button. Remember, you can change the shape of the rectangle anyway you want to give it a nice look.

Final code:

function rectangleClicked(evt:Event):void {
	myRectangle.alpha = 0.2;
}

myRectangle.addEventListener(MouseEvent.CLICK, rectangleClicked);

function rectangleOver(evt:Event):void {
	myRectangle.alpha = 0.5;
}

myRectangle.addEventListener(MouseEvent.MOUSE_OVER, rectangleOver);

function rectangleOut(evt:Event):void {
	myRectangle.alpha = 1;
}

myRectangle.addEventListener(MouseEvent.MOUSE_OUT, rectangleOut);

The Event type

You already know that when defining a function that responds to an event, you need an Event parameter for that function. Let me give you an example about this mysterious “Event” parameter. Type the following in the actions panel (we are still using the same rectangle “myRectangle”).

myRectangle.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(event:Event):void {
    trace("Type of event: " + event.type);
    trace("The event occured on: " + event.target.name);
}

Now test your movie. You should see the following when you click the rectangle.

As we can see, the event parameter tells us something about the occured event. Most importantly, it tells us what object caused the event. This comes very handy later on, when we use the same event handler for multiple objects. With the event parameter, we know which object caused the event.

ActionScript 3 Keyboard Events

In order to create a fully interactive flash movie, you need to know something about keyboard events. This tutorial is all about catching ActionScript 3.0 keyboard events and responding to them. So let’s get started!

Click on the stage and start pressing some buttons. See how the values change. Now let’s look the code behind this movie.

Moving to ActionScript 3.0

Here is the code behind the ActionScript keyboard event movie.

 
stage.addEventListener (KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener (KeyboardEvent.KEY_UP, keyUpHandler);
 
function keyDownHandler (e:KeyboardEvent):void {
 
	keyDownText.text =
	"Key code: " + e.keyCode + "\n" +
	"Ctrl status: " + e.ctrlKey + "\n" +
	"Key location: " + e.keyLocation + "\n" +
	"Shift key: " + e.shiftKey + "\n";
}
 
function keyUpHandler (e:KeyboardEvent):void {
 
	keyUpText.text = "Key code: " + e.keyCode;
}

As you can see, the code is really simple. The “keyDownText” and “keyUpText” are just dynamic text fields, where we put the keyboard event text. Here are the explanations for the keyboard event properties.

keyCode: Every keyboard button has a numerical key code value. You don’t need to remember them of course. For example, use this movie to find the key’s corresponding value.

ctrlKey: Tells whether the control key is pressed or not. There is also a same kind of property for the alt button called “altKey”.

keyLocation: This property indicates the location of the key on the keyboard. For example press the right shift button and see the location value for it. Then press the left shift button. As you can see, the location value changes. This is how you can differentiate same keys in the keyboard. This comes especially useful if you want to differentiate the keys between a numeric keypad and a standard keyboard.

shiftKey: Tells whether the shift key is pressed or not.

That’s it for this tutorial. Now you should be able to include keyboard interaction in your movies!

ActionScript 3 External Classes

This tutorial is all about external ActionScript 3 classes. I will teach you how to linkage movie clips to an ActionScript class and then we’ll create an external class.

The end product in seen above. The movie uses one external class and only a few lines of code is written in the main timeline. So why do we use external classes? To put it simple, external classes help you to stay more organized. External classes are part of a programming paradigm called “object oriented programming”. The subject is very broad, so I will not go into that. In this tutorial, you don’t need a great knowledge of OOP anyways. SO start your Flash IDE and let’s get started!

Setting up the environment

1. Create a new document of size 300×300.

2. Draw a star on the stage. The polystar will help you in that.

3. Convert the star into a movie clip. Give it a name “Star” and set the registration point to the center.

4. Linkage the movie clip to a class named “Star” (right click the movie clip in the library and select “Linkage”).

Don’t worry about the ActionScript Class Warning. It warns you, because Flash can’t find a class named “Star”. That’s normal since we haven’t created that class yet!

5. Remove the star from the stage.

Moving into ActionScript 3

6. Create a new ActionScript file.

7. Type the following in the class

package {

	import flash.display.MovieClip;
	import flash.geom.ColorTransform;
	import flash.events.*;

	/*
	This class represents the Star movie clip we drew on the stage.
	We extend this class to a movie clip, thus allowing us to use movie
	clip's functions and properties.
	*/
	public class Star extends MovieClip {

		private var starColor:uint;
		private var starRotation:Number;

		/*
		This is called the constructer of the class.
		It is called every time we create a new Star instance.
		In the constructor, we assign a random color to the star and set some
		of it's properties.
		*/
		public function Star () {

			//Calculate a random color
			this.starColor = Math.random() * 0xffffff;

			// Get access to the ColorTransform instance associated with star.
			var colorInfo:ColorTransform = this.transform.colorTransform;

			// Set the color of the ColorTransform object.
			colorInfo.color = this.starColor;

			// apply the color to the star
			this.transform.colorTransform = colorInfo;

			//Assign a random alpha for the star
			this.alpha = Math.random();

			//Assign a random rotation speed
			this.starRotation =  Math.random() * 10 - 5;

			//Assign a random scale
			this.scaleX = Math.random();
			this.scaleY = this.scaleX;

			//Add ENTER_FRAME where we do the animation
			addEventListener(Event.ENTER_FRAME, rotateStar);
		}

		//This function is responsible for the rotation of the star
		private function rotateStar(e:Event):void {
			this.rotation += this.starRotation;
		}
	}
}

8. Save the file as “Star.as” in the same directory where your main movie is (this is very important!). The movie won’t work without the correct file name and location. File names must always be the same as the class name.

9. You can close the ActionScript class now. Go to your main movie and type the following code in the first frame.

/*
Create 100 stars on the stage.
Assign a random position to each.
All the star animation etc. are done in the "Star" class.
*/
for (var i = 0; i < 100; i++) {
	var star:Star = new Star();
	star.x = stage.stageWidth * Math.random();
	star.y = stage.stageHeight * Math.random();
	addChild (star);
}

10. You are done, test your movie! I hope you enjoyed this tutorial and learned something from it

ActionScript 3 Color Picker

In this tutorial, I’ll show you how to change a movie clip’s color with ActionScript 3.0 using the color picker. So start up your Flash and let’s learn something new!

Setting up the environment

  1. First we add the color picker to the stage. In your “Components” window, drag the “ColorPicker” to the top left corner of the stage. If you don’t see the “Components” window, select Window -> Components (Ctrl + F7).
  2. Give the color picker an instance name of “myColorPicker”.
  3. Now draw a movie clip to the stage. It doesn’t matter what you draw, just make it white since that’s our starting color. I drew a star using the PolyStar Tool.
  4. Give your movie clip an instance name of “myStar”.
  5. Now let’s make the bottom text boxes. In the bottom left corner, draw a dynamic text field and type “Current color selected:”.
  6. . Draw another dynamic text field next to the first one. Don’t write anything there, just give it an instance name of “myCurrentColor”. We’ll be changing the text dynamically from ActionScript.

Moving into ActionScript 3.0

Create a layer for ActionScript and type the following.

import fl.events.ColorPickerEvent;
import flash.geom.ColorTransform;
 
//Set the color to white at the beginning
myColorPicker.selectedColor = 0xffffff;
 
// Get access to the ColorTransform instance associated with star.
var colorInfo:ColorTransform = myStar.transform.colorTransform;
 
//Add a listener that dispatches an event when user selects a new color
myColorPicker.addEventListener (ColorPickerEvent.CHANGE, colorChanged);
 
function colorChanged (e:ColorPickerEvent):void {
 
	// Set the color of the ColorTransform object.
	colorInfo.color = myColorPicker.selectedColor;
 
	// apply the change to the display object
	myStar.transform.colorTransform = colorInfo;
 
	//Show the selected color in the text field
	myCurrentColor.text = myColorPicker.hexValue;
}

You are done, hope you enjoyed this Flash ActionScript 3 tutorial