ActionScript3:Code Templates

From virtualMV2015wiki
Jump to: navigation, search
 Home  Flash10 (CS4) | Flash11 (CS5) <

Introduction

Use the following Code Templates in your own AS3 Movie

Icon Objective.png

Objective

By the end of this exercise you should:

  • Have a series of standard EventHandlers and Functions you can customise to suit your own AS3 project

Event Listeners

Using the .addEventListener

An ActionScript Event is any interaction within Flash, from mouse clicking, loading a new object to moving along the timeline. ActionScript 3 uses an Event Listener to listen for an event - such as a mouse click - and causes an action on a target. This is achieved by using the .addEventListener method. This method registers the mouse click so the target knows where to send the event object:

Sd eventmodel.png
Image modeled on one found in the book - Flash CS5 The Missing Manual [1]


ActionScript 3 has changed from ActionScript 2 in that you no longer apply the code directly to the object, now all code goes on the timeline.

The format is shown here:

myObject.addEventListener(Event, eventListenerFunction);
 
function eventListenerFunction (e:Event):void{
//ActionScript statement/s to be executed go here
}

Using the .addEventListener method is the backbone of interactivity with an ActionScript 3 movie.

Using the .removeEventListener

While the .addEventListener looks for an event to occur and causes a reaction, the .removeEventListener method can remove the reaction based on whatever conditions you apply.

The format is shown here:

myObject.removeEventListener(Event, eventListenerFunction);

A good example of this is using the add and remove methods to toggle a button event, eg. Clicking a button reveals and image, click again removes the image. Use IF statements to set the conditions. Set the button text to dynamically change as well within the same functions to "Show" "Hide" or some similar text with meaning to whatever scenario you are using.

For a small example using the .addEventListener and .removeEventListener to toggle a button event go to this small tutorial Using EventListeners to change a Button Event

Using the .addEventListener Method - Buttons and Navigation

Loading an external swf

ActionScript 3 no longer supports loadMovie to load an external swf into the current window. Use this code to achieve the same result:

Sd hottipicon.png
HOT TIP: Be careful with then naming of any object you have in the library. If an object in the main movie has the same name as an object in the swf you are loading, the object in the first movie will be used. Keep naming unique across all movies you intend to join together.


my_btn.addEventListener(MouseEvent.CLICK, loadSwf);
 
function loadSwf(e:MouseEvent):void {
var newMovieName:URLRequest = new URLRequest("newMovie.swf"); 
var loader:Loader = new Loader() 
loader.load(newMovieName); 
addChildAt(loader, 1);
}

Using addChildAt sets the z index of the new movie. In this case at level 1, or directly on top of the current movie. You can load at a lower level, but the new swf will remain hidden. You can also load into an empty movieClip positioned anywhere on the stage by appending addChild to the movieclip name:

emptyMovieClip.addChild(loader);

This actionscript can be used to load external images as well. All other script remains the same.

A variation of the above, giving the x and y coordinates to load the external swf:

var loader:Loader=new Loader();
	var mcExternal:MovieClip;
	this.addChildAt(loader, 1);
 
 
my_btn.addEventListener(MouseEvent.CLICK, loadSwf);
 
function loadSwf(e:MouseEvent):void {
	mcExternal=loader.content as MovieClip;
	loader.load(new URLRequest("newMovie.swf"));
	loader.x =0; //set the x coordinates
	loader.y =0; //set the y coordinates
}

Launching a swf inside a browser with the click of a button

Insert the following ActionScript on the frame one of the actions layer timeline within your movie. If you have the button inside another movieclip, you will need to insert this ActionScript on frame one of the movieclips timeline, not the main timeline. Just rename buttonName to match the name you have given the instance of your own button, launchName is the function name and can be anything appropriate, likewise targetName. Replace target.swf with you own swf name. "_self" will open the movie in the same browser window, remove if you want a new window to open.

buttonName.addEventListener(MouseEvent.CLICK, launchName);
function launchName(e:MouseEvent):void {
var targetName:URLRequest=new URLRequest("target.swf");
navigateToURL(targetName, "_self");
}

Moving along the timeline

Moving along the timeline differs little from ActionScript 2. The only thing to be aware of is that any instance of an object that you have called to the stage via ActionScript will remain there unless you get rid of it - don't expect an object to be gone just because you have inserted a new keyframe or blanked the stage. The secret is to use the .removeChild or .removeChildAt methods shown below. To advance along the timeline insert the following ActionScript - In this case using a button to initiate the gotoAndPlay to a frame label "menu". ActionScript 3 requires in a lot of instances, that you use labels instead of frame numbers.

buttonName.addEventListener(MouseEvent.CLICK, advanceFrame);
function advanceFrame(e:MouseEvent):void {
gotoAndPlay("targetFrameLabel") // or gotoAndStop("targetFrameLabel")
}

Removing Children

Any instance of an object you have called to the stage via ActionScript remains there until you use either the .removeChild or .removeChildAt methods to get rid of it. .removeChild lets you specify the instances name, and .removeChildAt lets you specify the level the object is at. In this example a button will return the user to a start page, and remove an object at level 1 and also an object called "nameofobject":

buttonName.addEventListener(MouseEvent.CLICK, gotoStartPage);
function gotoStartPage(e:MouseEvent):void {
 
	removeChildAt(1);
	removeChild(nameofobject);
	gotoAndStop("start");
}

If the object is on the maintimeline and you are trying to remove it say from a button within another movieClip on stage, you can try this:

	MovieClip(root).removeChildAt(1);
	MovieClip(root).removeChild(nameofobject);
}


Advancing to another Scene

According to quite a number of Flash Tutorial sites, its no longer good practice to uses Scenes within a Flash movie. But if you do decide to go with it, here's the code to advance to a new scene, using a button click event:
Sd hottipicon.png HOT TIP! It is important to use a frame label in this case, not a frame number.


newScene_button.addEventListener(MouseEvent.CLICK, gotoANewScene);
 
function gotoANewScene(e:MouseEvent):void {
 
gotoAndPlay("FrameOneLabel", "SceneName");
 
}

Mouse Events

Mouse Events allow Flash to react to a variety of mouse actions taken by the user. Below is a small list of events that are available in ActionScript 3.

Mouse Events in ActionScript 3:
CLICK Used to detect Mouse Clicks
DOUBLE_CLICK Used to detect double Clicks
MOUSE_DOWN Used to detect when the mouse is pressed down
MOUSE_LEAVE Used to detect when the mouse leaves the stage
MOUSE_MOVE Used to detect when the mouse moves
MOUSE_OUT Used to detect when a mouse move out of an attached object eg button
MOUSE_OVER Used to detect when the mouse moves over an attached object

Use the following code sample to attach the event listener to an object:

myObject.addEventListener(MouseEvent.CLICK, onMouseEvent);
 
function onMouseEvent(e:MouseEvent)
{
// your code to be implemented here
}

Separating your ActionScript from your FLA file

If you would like to store all your ActionScript in an Actionscript (.as) file, create a new file - File > New > ActionScript file. A new window opens, very similar to the Actions panel within the movie itself.

You can now write all your ActionScript in here, and attach it to you movie by entering the following code in frame One of your main movie:

include "myActionScriptFileName.as"

Garbage Collection

Garbage collection is a means by which Flash Player purges from memory objects that you no longer need. (Shupe, 2007)[2]. There are several optional parameters that you can add to the end of the .addEventListener() method, one of which facilitates garbage collection. The syntax is as follows:

eventTarget.addEventListener(EventType.EVENT_NAME, eventResponse, 
            useCapture:Boolean, priority:int, weakReference:Boolean);

useCapture:Boolean allows you to handle the listener once it reaches its target if its set to false - which is the default and will unlikely need to change from this.

priority:int allows you to order the execution of multiple listeners set to respond to the same event in the same phase. Set to 0 in the majority of cases.

weakReference:Boolean is the memory management option. Set this to true, so that when you are no longer referencing an object, the garbage collector knows it is marked for disposal and will purge it from memory.

The .addEventListener syntax would now read:

eventTarget.addEventListener(EventType.EVENT_NAME, eventResponse, false, 0, true);

This is the recommended optional parameters for Event Listeners (Shupe, 2007).

Resources

  • Adobe Flash Platform - Loading an external Swf [3]
  • Edutech Wiki - ActionScript 3 Event Handling [4]


Icon References.png References

  1. Grover, C. (2010). Flash CS5 The Missing Manual. Sebastapol, CA, United States of America: O'Reilly Media Inc.
  2. Shupe, R.(2007). Learning ActionScript 3 - A Beginners Guide, Sebastapol, CA, United States of America, OReilly Media Inc.
  3. Adobe Flash Platform - Loading an external Swf file (n.d.), Retrieved 23 August 2010, from http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7d9e.html
  4. Edutech Wiki Actionscript Event Handling (2009), Retrieved 22 August 2010, from http://edutechwiki.unige.ch/en/ActionScript_3_event_handling_tutorial

 

Day, S. (2010). ActionScript3:Code Templates. Retrieved December 12, 2017, from http://www.virtualmv.com/wiki/index.php?title=ActionScript3%3ACode_Templates