actionscript 3.0 programming pt. 1 - interactiondesign.se · introduction to actionscript 3.0...

38
ActionScript 3.0 programming pt. 1 (variables, data-types, statements, loops, functions, events) Thomas Lövgren [email protected] Introduction to “What is Flash?" At first, said it was hard to sum that up in just a few words. Then I thought for a moment and replied that Flash was a "powerful animating and programming tool...” Umeå Institute of Design, 2010-05-09

Upload: others

Post on 09-Oct-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

ActionScript 3.0 programming pt. 1

(variables, data-types, statements, loops, functions, events)

Thomas Lövgren

[email protected]

Introduction to

“What is Flash?" At first, said it was hard to

sum that up in just a few words. Then I thought for

a moment and replied that Flash was a "powerful

animating and programming tool...”

Umeå Institute of Design, 2010-05-09

Page 2: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Introduction to ActionScript 3.0

Workshop block 2 Outline

In this workshop we’ll discuss and practice the following topics:

ActionScript 3.0 overview

“Practical things” before/while programming AS3

Programming introduction, examples & exercises:

Variables

Data-types

Statements

Loops

Functions

Objects

Events

Page 3: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Variables

A variable is a place to store information

It has a name and a type

Variables are used to make the code dynamic

Values can generally be accessed or changed at any time

An identifier (usually a letter, word, or phrase) that is linked to a

value stored in the system's memory or an expression that can be

evaluated

Depending on the type-system of a programming language,

variables may only be able to store a specified data type

Page 4: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Naming variables

Variable-names can only contain letters, numbers, and dollar signs ($)

All variables must have unique names

Start variables with a lowercase letter

Variables are case-sensitive

Use mixed case for concatenated words

Don't use reserved words: this, menu, private, video, etc.

Don't use the same variable name with different cases

Keep variables as short as possible while retaining clarity

Example, with strict data-typing:var xSpeed:Number;

Page 5: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Data-types

The Data-type defines the type of data a variable or ActionScript

element can hold

Primitive data-types (Top level data-types):

Number, String, Boolean, int, Null, uint, and void

Complex data-types:

Array, Object, Date, Error, Function, RegExp, XML,

and XMLList

Page 6: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Variable syntax

Example of the different parts and structure of a variabledeclaration/population

Page 7: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Data-type: String

Strings are sequences of characters, numbers and punctuation marks. These are enclosed within double (") quotation marks

The default value for a variable declared with the String data-type is null

//declaration

var myURL_string:String;

//assignment

myURL_string = "www.flashkit.com";

//declaration and assignment

var myURL_string:String = "www.flashkit.com";

Page 8: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Data type: Number

The Number data type can represent integers, unsigned integers, and floating-point numbers

The default value is NaN

//declaration

var length:Number;

//assignment

length = 1100;

length = -22;

length = 0.00002234;

length = 100/3; //traces to 33.3333333333333

length = 1/0; //traces to Infinity

//initialization(declaration and assignment on the same code line)

var width:Number = 300;

Page 9: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Data type: Boolean

Boolean represents a boolean value, possible values: true or false

Converts the parameter expression to a Boolean value and returns

true or false

Default vaule is false

//declaration of a boolean variable

var isLoaded:Boolean;

//assignmet

isLoaded = true;

Page 10: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Array

Arrays are lists of data under which each item is identified by its order within the list

The first element in an Array has index 0

An array can be made up of primitive type values like strings, numeric values, booleans or complex type values like other arrays or objects

var music_array:Array = new Array();

music_array = ["Metallica", "Bruce Springsteen", "U2", "Iron

Maiden", "David Gray", "Van Morrison"];

music_array.length //traces the length of the array

music_array[1]; //traces Bruce Springsteen

var my_array:Array = [5,"Hello!",{a:5, b:7}]; //complex array

Page 11: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Arithmetic operators

Arithmetic operators

+, -, *, /, %

++, - -

+=, -=, *=, /=, %=

Increment ++, and decrement - -

Increments/decrements a variable by 1var x:Number = 10;

x++;

trace(x); //traces 11

x--;

trace(x); //traces 10

Page 12: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Precedence

The answer depends on operator precedence

var i:Number;

i = 12 + 3 * 10 / 2; //traces 27

You can override precedence by using parenteses

var i:Number;

I = (12 + 3) * 10 / 2;

trace(i); //traces 75

Page 13: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Conditional Statements

A way for the computer to make a choice based on some condition

”If it is dark, then light the lamp, if not, leave it off.”

The operator checks a specific condition for the statement(s)

The condition could be either true or false depending on the setup

The if - statement is the most important conditional statement in

ActionScript

if (statement_one operator statement_two){

//run code

}

Page 14: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

If & else-statement

Example of a if-statement with the operator ">"

(If var1 is greater than var2)

if(x > 100){ //statement

trace("X is too big"); //output

}

Instead of writing another if-statement you can use the else-

statement to catch when the condition evaluates to false

if(x > 100){

trace("X is too big");

}else{

trace("X is not too big");

}

Page 15: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Operators

Relational and Equality operators, evaluates to true or false

Operator Function/task== If var1 is equal to var2

>= If var1 is greater than or equal to var2

> If var1 is greater than var2

<= If var1 is smaller than or equal to var2

< If var1 is smaller than var2

!= If var1 is NOT equal to var2

&& If var1 and var2 exist or both var1 and var2 are both set to true

|| If either var1 and var2 exist and/or are set to true

Page 16: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Statements examples

if(hungry && !thirsty){ //hungry=true and thirsty=false

trace("go get a combo from the closest burger joint");

}

if((variable_1 == variable_2) && (variable_3 > variable_4)){

trace("variable 1 is equal to variable 2 and variable 3 is greater

than variable 4");

}

if(theTimeOfDay == theMorning){

trace("wake up");

} else if(theTimeOfDay == myBedTime){

trace("go to bed");

} else if(iShouldBeAtWork){

trace("working right now");

} else {

trace("watch some tv");

}

Page 17: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Switch Statement

Switch Staements are useful when you want to respond to a series of possible values that a variable might have (instead of writing long If-structures)

var switchExpression:int = 3; //declare variable

switch(switchExpression){ //switch statement

case 0:

trace(0);

break;

case 1:

trace(1);

break;

case 2:

trace(2);

break;

default:

trace("not case 0, 1, or 2"); //traces not case 0, 1, or 2

}

Page 18: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Loops

ActionScript loops are used to execute a segment of code repeatedly

for a number of times or while a certain condition is satisfied

This can save time and effort by not having to type the same code

multiple times to repeat a process

Example of loops:

For - loop

While - loop

Do/While loop

Note! In this lecture we will only discuss and practice the for-loop

Page 19: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Loops

Flowchart-example of a loop

Page 20: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

For - loop

The for-loop is probably the most commonly used because it is the most compact and the easiest to understand and use

The data-type int can be used as a counter-variable in a for-loop

Structure

for (counter; condition; action){

statements;

}

Example

for (var i:int = 0; i < 10; i++){ //for-loop

trace ("This code is repeated ten times"); //output

}

Page 21: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Array & Loops

Loops are very often used to manipulate and access the content of

arrays

var movie_array = new Array();

movie_array = ["Batman", "The Godfather", "Star Wars", "Lord of

The Rings", "Titanic"];

//loop through the array

for (var i:int = 0; i < movie_array.length; i++){

trace (movie_array[i]); //output

}

/* Batman

The Godfather

Star Wars

Lord of The Rings

*/ Titanic

Page 22: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Functions

Functions are blocks of code that carry out specific tasks and can be reused

Your function name should be unique and describe the value the function returns (same rules for namegiving as for variables)

A function can be called at any time by a function call

Functions can take parameters

A function should carry/have just one specific task

If a function does not return a value, it’s return type should be void

Tip! If you often write similar code segments, a function could save time and space

Page 23: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Function syntax

Example of the different parts and structure of a function declaration/contents

Page 24: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Function

The structure of a user defined function (two ways):

//example 1

function functionName([parameter0,..parameterN]):returnType{

// statement(s)

}

//example 2

functionName = function ([parameter0,..parameterN]):returnType{

// statement(s)

}

//example of a basic function

function showMsg():void{trace("I love ActionScript3!"); //output ”I Love ActionScript3!”

}

showMsg(); //function call

Page 25: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Function with parameters

This function takes two parameters, calculates and return the

area

//set up the function

function getArea(x:Number, y:Number):Number{ //return type:Number

return x * y; //calculate and return the area

}

getArea(100, 25); //function call, send parameters

Page 26: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Objects

In ActionScript 3.0, every object is defined by a class

The Object-class serves as the base class for all class definitions

A Class can be thought of as a template or a blueprint for a type

of Object

Objects are created by constructors using the new operator

syntax, and can have properties assigned to them dynamically

Functions defined in objects are known as methods

var myObject:Object = new Object(); //create a new object

myObject.property = value; //property for the object

Page 27: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Objects and methods

ActionScript contains a number of Built-in classes that are part of the

core language, for example: Date, Math, Mouse, Array, Keyboard,

String, XML etc

For example the Math or Date Class/Object have methods like:

var myDate = new Date(); //date object

myDate.getFullYear(); //object method: returns current year

//random Numbers

var rnd:int = Math.random(); //generates number between 0 and 1

var rnd:int = Math.random() * 10; //a number between 0 and 10

Page 28: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Custom Object

A Custom Object is a self-defined object where we can set up our

own set of properties for the object

A collection of properties describes the object

Ex. An apple has properties like smell, color, size and position

The object can contain different data types

Positve: Return the Object (all properties) in one function call

Example1 How to create a custom object:

var user:Object = new Object(); //create the object

user.name = "Irving"; //assign properties

user.age = 32;

user.hobby = "Drinking!";

Page 29: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Events

Why events? And why is it so important?

The answer is simple: We can’t have an interactive application

without detecting user inputs!

We need events for many different tasks, here’s a few examples:

Buttons: Press, release, rollOver, rollOut etc

Keyboard: Keypress, keyRelease etc

TextInput: Change, TextInput, Enter

Timer: Start and stop timer events

Loading data (Event complete)

Animations (Frame Event)

Page 30: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Event handling

For Event Handling in AS3, there are tree important steps we want

to identify:

1. The event source: Which object is the event is going to happen

to? For instance, which button will be clicked etc

2. The event: What’s going to happen, the thing that we want to

respond to?

3. The response: What step(s) should be performed when the event

happens?

Page 31: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

EventListener and Handler

For each event (user action or something else), we need to register a an event listener and an event handler/function

Let’s look at the basic syntax of this:

//add eventlistener to object, specify the event, call the function

eventTarget.addEventListener(EventClass.EVENT_NAME, eventHandler);

//the event handler/function

function eventHandler(eventObject:EventType){

//actions performed in response to the event go here

}

Note! The addEventListener()-method can have 5 parameters, the first two are compulsory

Page 32: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

MouseEvent

The MouseEvent class is useful for activities like: Mouse clicks, mouse

navigation, drag and drop, roll over/roll out, drawing by mouse etc

In this example we use an event called CLICK for detection of a

mouse click

//add eventlistener to object, specify the event, call the function

my_button.addEventListener(MouseEvent.CLICK, clickHandler);

//handler/function that proceeds the action

function clickHandler(event:MouseEvent){

trace(”Button click: Testing Listener and Handler!”);

}

Note! The argument in the handler/function contains information about the event

Page 33: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

KeyboardEvent

The KeyboardEvent class is useful for activities like: Keyboard

navigation, keyPress, tabbing etc

In this example we use the an event called KEY_DOWN for

detection of a keyPress

//add eventlistener to object, specify the event, call the function

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);

//handler/function that proceeds the action

function keyDownHandler(event:KeyboardEvent){

trace("You just pressed a key!");

}

Page 34: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Common Events

Some of the most common events for Mouse and Keyboard (with a

migration guide between AS2 and AS3):

Page 35: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

removeEventListener

It’s a good idea to remove listeners that we know will no longer be

needed. This could easily be done by the removeEventListener method

The removeEventListener method requires two parameters: The event

and the function specified when the listener was created

For example like this:

//remove the listener from button

my_button.removeEventListener(MouseEvent.CLICK, clickHandler);

Page 36: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

MouseEvent(Random number)

This example generates a random number between 0-100 on every

mouse click, the numbers will appear in a dynamic text field

//add eventlistener to object, specify the event, call the function

rnd_button.addEventListener(MouseEvent.MOUSE_DOWN, randomNumber);

//handler/function that proceeds the action

function randomNumber(event:MouseEvent):void{

rnd = Math.random() * 100; //generate a random number between 0-100

random_txt.text = String(rnd); //cast number to string, output

}

Page 37: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

Timer Event

The Timer class is very useful if we want to fire an event within an

interval (with a specific delay)

The Timer Object can have two parameters (delay, repeatCount)

delay is compulsory

The start method starts the timer (there’s also a stop method)

//example of using the timer, delay and repeatCount

var timer:Timer = new Timer(1000, 5); //1000 miliseconds = 1 sec

//add listener and call the onTimer function/handler

timer.addEventListener(TimerEvent.TIMER, onTimer);

timer.start(); //start timer

function onTimer(event:TimerEvent):void{ //function/handler

trace(”Timer ticking!”); //output

}

Page 38: ActionScript 3.0 programming pt. 1 - interactiondesign.se · Introduction to ActionScript 3.0 Workshop block 2 Outline In this workshop we’ll discuss and practice the following

FrameEvent

The Frame event is very useful for all kinds of animations, it’s

basically a frame loop - the event occurs at the rate of the frame rate

Let’s say out movie has a frame rate of 30 fps, then the event will be

called 30 times a second

//add the listener to the movieClip, event class, function call

my_mc.addEventListener(Event.ENTER_FRAME, enterFrameHandler);

//function/handler that animates a movieClip

function enterFrameHandler(event:Event){

my_mc.x += 5; //move the clip 5 pixels right every enterframe

}

Note! More of this in the AS3 Animation/Motion lecture…