Sie sind auf Seite 1von 3

Flash ActionScript Program Flow Control setInterval, clearInterval

Repeatly execute a function (or an object).


if (condition){ if (age>=18) {
Quick Reference statement(s); trace("welcome, user"); \\========= Example=========
Author: Jialong He } else { } var intervalId:Number;
Jialong_he@yahoo.com statement(s); else { var count:Number = 0;
http://tiger.la.asu.edu } trace("sorry, junior"); var maxCount:Number = 10;
} var duration:Number = 20;
Introduction for (init; condition; next) { for (Cnt = 1; Cnt<10; Cnt++) {
function myCallback():Void {
statement(s); trace(Cnt);
Using Flash to create animations on the web is popular because the flash } } trace(count);
player is installed on most computers and the published flash file (SWF if(count >= maxCount) {clearInterval(intervalId);}
file) is small. Flash has a powerful scripting language called ActionScript. count++;
You can use write script to manipulate and control objects on the stage. Its switch (expression){ Switch (myChar) {
}
syntax is similar to JavaScript (or C++). caseClause: case "A" :
intervalId = setInterval(this, "myCallback", duration);
[defaultClause:] case "a" :
Note: this quick reference is based on ActionScript 2.0 language reference. } trace("you pressed A or a");
break; escape, unescape Converts the parameter to a string and
Script Example default : encodes it in a URL-encoded format, where
trace("you did not press A"); all nonalphanumeric characters are replaced
A script can be associated with a keyframe or with an object. To test the with % hexadecimal sequences (e.g, @ to
}
following script, copy it to the action panel. Press “Ctrl + Enter” to start the %40).
flash file. for (var in object) { var myObject:Object = {Name:"Tara",
statement(s); age:27, city:"San Francisco"}; getProperty, setProperty Get (set) movie clip property
//==================== }
// A simple ActionScript for (var prop in myObject) { getURL Load a web page in browser
//==================== trace(myObject[prop]);
on (event) { Mouse/ket event handler
for (Cnt=1; Cnt<10; Cnt++) { }
Press, release, releaseOutside, rollOut,
trace(Math.random()); while(condition) { var Cnt:Number = 0; } rollOver, dragOut, dragOver, keyPress
} statement(s); while (Cnt < 20) {
trace ("Hello, World!"); } trace(Cnt); e.g.; on (press) { startDrag(this); }
i += 3;
onClipEvent(movieEvent: Movie clip event handler. load, unload,
}
Object) { enterFrame, mouseMove, MouseDown,
Operator do { statement(s) } while var myVar:Number = 0; statements; MouseUp, KeyDown, KeyUp, Data.
+, -, *, /, % Add, Subtract, Multiply, Division, Remainder (condition) do { }
+=, -=, *=, =/, =% Combine with assignment operator trace(myVar); onClipEvent (keyDown) {
myVar++; if (Key.getCode() == Key.RIGHT) {
++, --, [] Increase, decrease, Array access } while (myVar < 5); this._parent.nextFrame();
==, !=, <, <=, >, >= Comparison, equal, not equal, less than, … function FName(P){ function mySquared(x:Number) { } else if (Key.getCode() == Key.LEFT) {
!, &&, || Logical NOT, AND, OR statement(s) return Math.pow(x, 2); this._parent.prevFrame();
} } }
<<, >>, >>> Bit shift, left, right, right unsigned }
~, &, |, ^ Bitwise NOT, AND, OR, XOR class, interface, implement, Define custom class related statements
dynamic, extend, private, startDrag, stopDrag Makes the target movie clip draggable while
new, delete Allocate (delete) an object public, intrinsic the movie plays.
typeof, instanceof get expression type, test an instance
my_mc.onPress = function () {
//, /* */ One line and multiple line comments
startDrag(this);
Global Functions }
play, stop, nextFrame, prevFrame Main timeline movie clip play head my_mc.onRelease = function() {
Constants and Compiler Directives gotoAndPlay, gotoAndStop control stopDrag();
Predefined constants nextScene, prevScene }
true, false, undefined,
null, NaN, Infinity loadMovie, loadMovieNum Loads (unload) a SWF, JPEG, GIF, fscommand Lets the SWF file communicate with either
newline unloadMovie, unloadMovieNum or PNG file from local disk or web Flash Player or the program that is hosting
Initialization actions are executed only once server into a movie clip Flash Player, such as a web browser.
#initclip
statements(s) when a SWF file is played loadVariables, loadVariablesNum Reads data from an external file
either on local disk or on web server e.g, fscommand("fullscreen", true);
#endinitclip
isFinite, isNaN Test number
#include “filename.as" Include external ActionScript
getVersion , targetPath, Miscellaneous functions.
trace, getTimer,
removeMovieClip Math Mouse
duplicateMovieClip
Properties E, LN10, LN2, LOG10E, LOG2E, PI, SORT1_2, SORT2 Events onMouseDown, onMouseMove, onMouseUp, onMouseWheel
Methods abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, Methods addListener, hide, removeListener, show
pow, random, round, sin, sqrt, tan Example var mouseListener:Object = new Object();
Global Properties
Example trace(Math.log(0)); // output: -Infinity
_global A reference to the global object that holds the trace(Math.atan(-1)); // output: -0.785398163397448 mouseListener.onMouseDown = function() {
core ActionScript classes, such as String, trace("Mouse down");
Object, Math, and Array. };
_parent Specifies or returns a reference to the movie clip String mouseListener.onMouseMove = function() {
or object that contains the current movie clip trace(_xmouse);
or object. Properties length trace(_ymouse);
Methods charAt, charCodeAt, concat, fromCharCode, indexOf, };
_root Specifies or returns a reference to the root movie
lastIndexOf, slice, split, substr, substring, toLowerCase, mouseListener.onMouseUp = function() {
clip Timeline.
toString, toUpperCase, valueOf trace("Mouse up");
This References an object or movie clip instance. };
Example var my_str:String = new String("Hello world");
Mouse.addListener(mouseListener);
var mySubstring:String = new String();
Common Classes mySubstring = my_str.substr(6,5);
Object trace(mySubstring); // output: world
Button
constructor Object trace (mySubstring.toUpperCase()); //WORLD Properties _alpha, blendMode, cacheAsBitmap, enabled, filters,
Properties constructor, _proto_, prototype, _resolve, _focusrect, _height, _highquality, menu, _name, _parent,
Methods addProperty, hasOwnProperty, isPropertyEnumerable, _quality, _rotation, scale9Grid, _soundbuftime, tabEnabled,
isPrototypeOf, registerClass, toString, unwatch, valueOf, Stage tabIndex, _target, trackAsMenu, _url, useHandCursor,
watch _visible, _width, _x, _xmouse, _xscale, _y, _ymouse, _yscale
Properties align, height, scaleMode, showMenu, width
Events onDragOut, onDragOver, onKeyDown, onKeyUp,
Event onResize
onKillFocus, onPress, onRelease, onReseaseOutside,
Array Methods addListener, removeListener onRollOut, onRollOver, onSetFocus
Properties CASEINSENSITIVE, DESCENDING, length, NUMRIC, Example Stage.scaleMode = "noScale" Methods getDepth
RETURNINDEXEDARRAY, UNIQUESORT var myListener:Object = new Object();
Example myBtn1_btn.enabled = true;
myListener.onResize = function () {
Methods concat, join, pop, push, reverse, shift, slice, sort, sortOn, splice, myBtn2_btn.enabled = false;
trace("Stage size is now " + Stage.width + " by " +
toString, unshift. Stage.height);
myBtn1_btn.onRelease = function() {
Example var myA:Array = new Array("a","b","c"); }
trace( "you clicked : " + this._name );
var myN:Array = new Array(1,2,3); Stage.addListener(myListener);
};
var myAN:Array =myA.concat(myN);
myBtn2_btn.onRelease = function() {
trace(myAN.length);
trace( "you clicked : " + this._name );
// Creates array [a,b,c,1,2,3].
Key };
Properties BACKSPACE, CAPSLOCK, CONTROL, DELETEKEY,
DOWN, END, ENTER, ESCAPE, HOME, INSERT, LEFT,
Date PGDN, PGUP, RIGHT, SHIFT, SPACE, TAB, UP, _listeners TextFormat
Properties Only have properties inherited from Object. Events onKeyDown, onKeyUp Constructor TextFormat
Methods getDate, getDay, getFullYear, getHours, getMilliseconds, Methods addListener, getAscii, getCode, isAccessible, isDown, Properties align, blockIndent, bold, bullet, color, font, indent, italic,
getMinutes, getMonth, getSeconds, getTime, isToggled, removeListener kerning, leading, leftMargin, letterSpacing, rightMargin,
getTimezoneOffset, getYear, setDate, setFullYear, setHours,
Example var myListener:Object = new Object(); size, tabStops, target, underline, url
setMilliseconds, setMinutes, setMonth, setSeconds, setTime,
setYear, toString, valueOf, (most functions have UTC ones) myListener.onKeyDown = function () { Methods getTextExtent
trace ("You pressed a key.");
Example var my_date:Date = new Date(2004,4,25); Example var my_fmt:TextFormat = new TextFormat();
}
trace(my_date.getYear()); // output: 104 my_fmt.bold = true; my_fmt.font = "Arial";
myListener.onKeyUp = function () {
trace(my_date.getFullYear()); // output: 2004 my_fmt.size = 12; my_fmt.color = 0xFF0000;
trace ("You released a key.");
my_date.setYear(99); }
trace(my_date.getYear()); // output: 99 this.createTextField("stats_txt", 5000, 10, 0, 530, 22);
Key.addListener(myListener);
trace(my_date.getFullYear()); // output: 1999 stats_txt.setNewTextFormat(my_fmt);
Video XMLNode
TextField Properties _alpha, deblocking, _height, height, _name, _parent, _rotation, Constructor XMLNode
smoothing, _visible, _width, width, _x, _xmouse, _xscale, _y, Properties attributes, childNodes, firstChild, lastChild,localName,
Properties _alpha, antiAliasType, autoSize, background,
_ymouse, _yscale namespaceURI, nextSibling, nodeName, nodeType,
backgroundColor, border, borderColor, bottomScroll,
condeseWhite, enbedFonts, filter, gridFitType, _height, Methods attachVideo, clear nodeValue, parendNode, prefix, previousSibling
_highquality, hscroll, html, htmlText, length, maxChars, Example var my_video:Video; Methods appendChild, cloneNode, getnamespaceForPrefix,
maxhscroll, maxscroll, menu, mouseWheelEnabled, multiline, var my_nc:NetConnection = new NetConnection(); getPrefixForNamespace, hasChildNodes, removeNode,
_name, _parent, password, _quality, restrict, _rotation, scroll, my_nc.connect(null); toString
selectable, sharpness, _soundbuftime, styleSheet, tabEnabled, var my_ns:NetStream = new NetStream(my_nc);
tabIndex, _target, text, textColor, textHeight, textWidth, my_video.attachVideo(my_ns);
thickness, type, _url, variable, _visible, _width, wordWrap, _x, my_ns.play("video1.flv");
_xmouse, _xscale, _y, _ymouse, _yscale
Event onChanged, onKillFocus, onScroller, onSetFocus
Methods addListener, getDepth, getFontList, getNewTextFormat, MovieClip XML
getTextFormat, removeLisener, removeTextField, replaceSel, Properties _alpha, blendMode, cacheAsBitmap, _currentframe, Constructor XML
replaceText, setNewTextFormat, setTextFormat _droptarget, enabled, filters, focusEnabled, _focusrect, Properties contenttype, docTypeDecl, idMap, ignoreWhite, loaded,
Example my_txt.border = true; _framesloaded, _height, _highquality, hitArea, _lockroot, status, xmlDecl
my_txt.type = "input"; menu, _name, opaqueBackground, _parent, _quality, _rotation,
scale9Grid, scrollRect, _soundbuftime, tabChildren, Events onData, onHTTPStatus, onLoad
my_txt.onChanged = function(textfield_txt:TextField) { tabEnabled, tabIndex, _target, _totalframes, trackAsMenu, Methods addRequestHeader, createElement, createTextNode,
trace(textfield_txt._name+" changed"); transform, _url, useHandCursor, _visible, _width, _x, getBytesLoaded, getBytesTotal, load, parseXML, send,
}; _xmouse, _xscale, _y, _ymouse, _yscale sendAndLoad
Methods attachAudio, attachBitmap, attachMovie, beginBitmapFill, Example var myXML:XML = new XML();
var txtListener:Object = new Object(); beginFill, beginGradientFill, clear, createEmptyMovieClip, myXML.ignoreWhite = true;
txtListener.onChanged = function(textfield_txt:TextField) { createTextField, curveTo, duplicateMovieClip, endFill,
trace(textfield_txt._name+" changed and notified getBounds, getBytesLoaded, getBytesTotal, getDepth, myXML.onLoad = function () {
myListener"); getInstanceAtDepth, getNextHightsDepth, getRect, trace(this.childNodes);
}; getSWFVersion, getTextSnapshot, getURL, globalToLocal, }
my_txt.addListener(txtListener); gotoAndPlay, gotoAndStop, hitTest, lineGradientStyle,
lineStyle, lineTo, loadMoive, loadVariables, localToGlobal, myXML.load ("flute.xml");
moveTo, nextFrame, play, prevFrame, removeMovieClip,
setMask, setMask, startDrag, stop, stopDrag, swapDepths,
Sound unloadMovie
constructor Sound Events onData, onDragOut, onDragOver, onEnterFrame,
onKeyDown, onKeyUp, onKillFocus, onLoad, onMouseDown, XMLsocket
Properties duration, id3, position
onMouseMove, onMouseUp, onPress, onRelease, Constructor XMLSocket
Events onID3, onLoad, onSoundComplete onReleaseOutside, onRollOut, onRollOver, onSetFocus, Events onClose, onConnect, onData, onXML
Methods attachSound, getBytesLoaded, getBytesTotal, getPan, onUnload
Methods close, connect, send
getTransform, getVolume, loadSound, setPan, Example this.createEmptyMovieClip("triangle",
setTransform, setVolume, start, stop this.getNextHighestDepth()); Example var socket:XMLSocket = new XMLSocket()
socket.onConnect = function (success:Boolean) {
Example var my_sound:Sound = new Sound();
triangle.beginFill(0x0000FF, 100); if (success) {
my_sound.attachSound("logoff_id");
triangle.moveTo(10, 10); trace ("Connection succeeded!")
triangle.lineTo(10, 100); } else {
my_sound.onSoundComplete = function() {
triangle.lineTo(100, 10); trace ("Connection failed!")
trace("mySoundID completed");
triangle.lineTo(10, 10); }
};
}
triangle.onRollOver = function() { if (!socket.connect(null, 2000)) {
my_sound.start();
this._alpha = 50; trace ("Connection failed!")
}; }
triangle.onRollOut = function() {
this._alpha = 100;
};