Animation
ActionScript and Test Movie
ActionScript is the scripting language of Flash movies and games: buttons that answer clicks, clips that follow the keys, scores kept in text fields. Phoenix writes it in the Actions panel and plays it in Test Movie, ActionScript 1 and 2 as older movies have it and ActionScript 3 frame scripts with their event listeners. HTML5 Canvas documents' JavaScript plays there too.
To make a character or a menu answer clicks and keys without writing ActionScript, use the States panel: frame labels become states, and arrows between them say what sends the playhead from one to another. Phoenix writes the script for you.
Where scripts go
A script belongs to one of two places:
- A keyframe
- It runs each time the playhead reaches that frame: on the main timeline, or inside a movie clip as the clip plays. Most scripts go here, and in ActionScript 3 all of them do. A layer named actions at the top of the timeline, with nothing else on it, keeps them easy to find.
- A button or movie clip instance
- ActionScript 1 and 2 only. A button's script holds handlers such as
on (release) { ... }, run when it is clicked; a movie clip's holdsonClipEvent (enterFrame) { ... }and the like.
Scripts reach movie clips, buttons and text fields by their instance names, set in the Properties panel: a clip named hat is hat to the script on its timeline. Library symbols are reached by their linkage, set in the library's symbol properties (exported for ActionScript, with an identifier or a class name).
The Actions panel
(F9) shows the script of the keyframe at the playhead on the current layer, ready to type into. Select a button or movie clip instance on the stage instead and it shows that instance's own script.
- What you type goes into the document as you type. Each script you work on is one step in the undo history until you move to another script or click away, so Ctrl+Z on the stage takes back the whole edit. Inside the editor, Ctrl+Z undoes typing.
- The script navigator on the left lists every script in the document, scene by scene and symbol by symbol. Click one to edit it without moving the playhead. The ☰ button shows or hides it.
- Pin keeps the script in the panel while you select other things and move the playhead. Picking a script in the navigator pins it; click Pin again to follow the selection.
- Check checks the script's syntax. It is also checked each time it goes into the document: the line with an error is marked, and the line below the editor says what is wrong.
Writing code
- Code hints. Type a dot and what can follow it is offered: a clip's methods and properties,
MouseEvent.'s events,Key.'s keys. Ctrl+Space offers every word that fits what you have begun, the instance names on the timeline among them. Arrow to one and press Enter or Tab; Esc closes them. - Snippets puts in ready-made code for what movies often do: stop at a frame, go to a frame on a click, show or hide, drag and drop, move with the arrow keys, count clicks in a text field, play a library sound. Those for ActionScript 2 go in a button's or clip's script; those for ActionScript 3, and the JavaScript ones for HTML5 Canvas documents, in a frame's. A snippet that works on an instance asks which.
- Target (Insert Target Path) lists the named movie clips and buttons the script can reach, those inside them too, and types the path to the one you pick at the caret:
this.hat.bow, or from the root (_root.hat.bow, orexportRoot.hat.bowin an HTML5 Canvas document) for a script on a scene's timeline. Only instances with a name are listed. - Find (Ctrl+F) finds, and Ctrl+H replaces. Ctrl+G goes to a line, and Ctrl+/ comments the selected lines out or back in.
- Tab and Shift+Tab indent and outdent the selected lines. A new line keeps the indent, one step deeper after an opening brace, and a closing brace steps back.
ActionScript files (.as) open in , the same editor in a window of its own; see Write a script.
Test Movie
(Ctrl+Enter) plays the movie in a window of its own as Flash Player would, at the document's frame rate, running its ActionScript. It starts at the first scene and plays the scenes in turn, back to the first after the last. Buttons light up under the mouse and answer clicks, and keys typed in the window go to the movie, so an interactive movie, such as a dress-up game, can be played.
- The first button, Restart, plays it again from the first frame.
- Pause holds it where it is (it then shows Play); Step moves the paused movie on one frame at a time.
- The time slider shows where the scene is; click or drag it to go to another frame, whose scripts run as a
gotoAndPlaywould run them. Beside it are the scene and frame, and whether the timeline has stopped. - Esc, or closing the window, goes back to editing. Playing never changes the document.
Buttons and movie clips are clicked by their art, so a click between two buttons finds neither. Click an input text field to type into it.
ActionScript 1 and 2
As older movies and games are written, they run as Flash Player runs them:
- Frame scripts run as their keyframes are reached, on the main timeline and in every movie clip, after the frame's objects are placed.
stop(),play(),gotoAndPlay(),gotoAndStop(),nextFrame()andprevFrame(), on the timeline or on a named clip (hat.gotoAndStop(3)), andtellTarget.nextScene()andprevScene(), and gotos that name a scene (gotoAndPlay("Ending", 1)) or a label in another scene.on (release),on (press),on (rollOver)and the other button events,on (keyPress "<Left>"), andonClipEvent (load),(enterFrame),(keyDown),(keyUp),(mouseDown),(mouseUp)and(mouseMove)on movie clips.- A clip's
_x,_y,_visible,_alpha,_xscale,_yscale,_rotation,_width,_height,_currentframe,_totalframes,_xmouseand_ymouse, read and set by dot (hat._visible = false) or withgetPropertyandsetProperty, and clips found by name or by path ("/hat",_root.hat,_parent). - The keyboard:
Key.isDown(Key.LEFT),Key.getCode(),Key.getAscii()andKey.addListener(). Selection.setFocus("name_txt")andgetFocus(), for input fields.- Variables,
if, loops, functions (constructor functions withnewtoo), arrays and objects,ifFrameLoaded(everything counts as loaded) andtrace(), whose output goes to the Output panel (F2).
ActionScript 3
An ActionScript 3 movie (as its publish settings say) plays with the flash.* classes, over the display list: everything on the stage is a display object scripts can find, move, filter, draw into and take apart, and every class can be made with new, extended, and tested with is and instanceof.
- The display list.
Sprite,Shape,MovieClip(its frames, labels and scenes:currentFrame,currentLabel,currentLabels,scenes,gotoAndStopwith a scene,addFrameScript),SimpleButton,Bitmap,TextField, and theStage(stageWidth,frameRate,focus,invalidate()and the rest). Children are added, removed, reordered and found by name; objects have their position, scale, rotation, alpha, filters, blend mode, mask, scroll rect,transform, bounds, and hit tests. What the timeline places is the same objects: a frame's named instances are its timeline's variables, and a class that declares them gets them. - Drawing.
graphics: lines, fills (solid, gradient and bitmap), rectangles, circles, ellipses, curves,drawPathanddrawTriangles.BitmapDatawith all its methods, fromgetPixel32andfillRecttodraw,copyPixels,threshold,applyFilter,floodFillandperlinNoise. - Events.
EventDispatcherwith capture, target and bubble phases, priorities,stopPropagationandpreventDefault;Event,MouseEvent,KeyboardEvent,FocusEvent,TextEvent,TimerEvent,ProgressEvent,IOErrorEventand the rest. Classes of your own may extendEventDispatcherorEvent; an event sent again goes as itsclone(). The pointer and the keys reach what is under them and the focus, and the stage hears every key. - Geometry and filters.
Point,Rectangle,Matrix,ColorTransformandTransform;BlurFilter,DropShadowFilter,GlowFilter,BevelFilter, the gradient filters,ColorMatrixFilterandConvolutionFilter(a display object'sfiltersare copies, as the player keeps them);fl.motion.AdjustColor. - Data, time and the web.
ByteArray(every read and write, both byte orders,compressanduncompress),Timer,setTimeout,setIntervalandgetTimer, which keep the movie's time.URLLoaderloads text, bytes and variables, andLoaderloads PNG, JPEG and GIF images, from files beside the movie or from the web;navigateToURLopens web pages in your browser. Anything the movie sends to the web is shown in the Output panel;navigateToURLsends no form data, and says so.SharedObject.getLocalkeeps what a movie saves with Phoenix's settings. - Library symbols are classes. A symbol exported for ActionScript is its class:
new CloseButton()makes one,getDefinitionByName("CloseButton")finds it, and each instance a timeline places is one, its constructor run as it is placed and before the frame's scripts. A symbol without a class file gets the class the player would make for it. Bitmaps and sounds exported for ActionScript areBitmapDataandSoundclasses. - Frame scripts belong to their timeline: what frame 1 declares, later frames see,
thisis the timeline, and theflash.*classes need noimport. With a document class, they run in its instance. - Components. The
fl.controlscomponents (Button, CheckBox, ComboBox, List, Slider and the rest) are Phoenix's own, written in ActionScript: placed on the stage, they take the parameters set in the Component Parameters.
Class files
An ActionScript 3 movie can keep its code in class files (.as). Test Movie loads each class the first time a script needs it, by its name: game.Hat is game/Hat.as, looked for in turn in the document's folder, the source paths in its publish settings, the sources kept beside a library the publish settings list (the src folder beside a .swc's lib folder), any src folder in the document's folder or the folders in it, the class paths in , and last Phoenix's own classes.
- The document class, named in the publish settings, is the main timeline's: its constructor runs before the first frame's scripts, with the first frame's instances placed, and frame scripts see its methods and fields.
- A symbol's class, its linkage class name, is what each clip of the symbol is.
A class that does not compile shows its file and line in the Output panel, as a frame script does. compiles the same classes into the SWF movie (see SWF movies), and translates them to JavaScript for an HTML5 page, so the movie's scripts, its classes and its components run in any browser (see HTML5 pages).
Published movies
An SWF movie opened in Phoenix keeps the ActionScript 3 compiled into it, and Test Movie runs it: the main timeline is an instance of the movie's own main timeline class, each symbol linked to a class is that class, and the frame scripts are the ones that class gives its frames. The classes compiled into the movie come first, so a movie built with the components runs its own copies of them rather than Phoenix's. A movie that loads shared libraries before it starts (a preloader for text layout framework text) plays the movie it would load.
- The compiled code runs as published, with no source to show: an error names the class and method it stopped in, with the place in the method's code.
- Text layout framework text, which comes from a shared library rather than the movie, shows as plain text in its box, in the font, size and color of its first run.
- Saved as a document, the movie keeps its compiled code (in
bin/abc) and still runs it in Test Movie; the code itself cannot be edited.
A movie published with ActionScript 1 or 2 keeps that compiled too, and Test Movie and Phoenix play run it as a player would: each frame's actions when the frame is reached, a symbol's #initclip actions before the frame that first needs it, buttons' on() handlers (key presses among them) and movie clips' onClipEvent() handlers. The frames that had scripts carry a comment saying so, as the code cannot be turned back into source. Prototypes, Object.registerClass, ActionScript 2 classes, onEnterFrame, setInterval and the oldest actions (tellTarget, slash paths such as /hat:size, getProperty) all run; names are found whatever their case in movies published for player 6 and before, as they were then. Loading other movies and variables (loadMovie, loadVariables) is not done.
HTML5 Canvas JavaScript
An HTML5 Canvas document's scripts are JavaScript, written for CreateJS, the library its published web page plays with. Make one with , choosing HTML5 Canvas as the Platform; a Canvas document made elsewhere opens as one, and keeps its publish settings when saved. The Actions panel edits and checks its scripts as JavaScript, with JavaScript snippets, the Document Info in the Properties panel shows its Platform, and Test Movie runs it:
- Frame scripts run as their keyframes are reached, on the main timeline and in every movie clip, each as a function of its own:
thisis the timeline, and what a script declares withvaris its own, so keep what later frames need on the timeline (this.score = 0). - Timelines.
stop(),play(),gotoAndPlay()andgotoAndStop()by frame number or label. Frames count from 0 in JavaScript:this.gotoAndStop(0)goes to the first frame.currentFrame(from 0 too),totalFrames,currentLabel,labels,paused, andloop = falseto stop on the last frame. - Instances by name:
this.ball, withx,y,rotation,scaleX,scaleY,alpha,visible,name,parent,children,mouseEnabledandcursor = "pointer"(a hand over it);skewX,skewY,regXandregY,setTransform();localToGlobal,globalToLocal,getBoundsandhitTest. As in CreateJS, every instance a timeline has is there from the start: a script reaches an instance whose keyframe is still to come, and an instance a later keyframe places again is the same object, its listeners and properties with it, started again from its first frame. Text fields:this.score_txt.text = "Score: " + score.exportRootis the main timeline andstagethe stage, withmouseX,mouseYandcanvas.width. - Events.
addEventListener,removeEventListener,on()(with its scope, once and data) andoff(), anddispatchEventfor events of your own. Clips hearclick,dblclick,mousedown,mouseup,mouseover,mouseout,rollover,rollout,pressmove,pressupandtick; the stagestagemousedown,stagemouseupandstagemousemove;windowanddocumenthearkeydownandkeyup. Mouse events go up from the clip under the pointer to the main timeline, andstopPropagation()stops them.function () { ... }.bind(this)works as in a browser. - Time.
createjs.Ticker(framerate,getTicks(),getTime()and itstickevent);createjs.Tween.get(this.ball).to({x: 300}, 1000, createjs.Ease.quadOut), withwait,call,setandloop, and thecreatejs.Easecurves;setTimeoutandsetInterval. All of them keep the movie's time. - The library.
new lib.Ball()makes a clip of a library symbol, by its linkage or its name, or aBitmapof a library bitmap;images.photois a library bitmap by its name, forBitmap,SpriteSheetand bitmap fills.addChild,addChildAt,removeChild,setChildIndex,swapChildrenandsortChildrenput objects on a timeline, in aContainer, or on thestage.createjs.Sound.play("linkage")plays a library sound. - Drawing.
new createjs.Shape()and itsgraphics:beginFill,beginStroke,setStrokeStyle, linear, radial and bitmap fills and strokes,moveTo,lineTo,quadraticCurveTo,bezierCurveTo,arc,arcTo,closePath,drawRect,drawRoundRect,drawRoundRectComplex,drawCircle,drawEllipse,drawPolyStarandclear, chained, in the short forms too (g.f("red").dc(0, 0, 20)), and the encoded paths of exported art (p()). Colors are CSS colors ("#f80","rgba(0,0,0,0.5)","gold"). Change agraphics.command(circle.radius = 30) to animate the drawing. - Text, bitmaps and sprites.
new createjs.Text("Score", "bold 24px Arial", "#fff")withtextAlign,textBaseline,lineWidth(wrapping),lineHeight,maxWidth,getMeasuredWidth()andgetMeasuredHeight().new createjs.Bitmap()from a library bitmap, an image file beside the document ("images/hero.png"), anew Image(), or a cached object'scacheCanvas, withsourceRect.createjs.SpriteSheetandcreatejs.Spriteplay frames cut from images, with animations,gotoAndPlayandanimationend. - Clips made in code.
new createjs.MovieClip()plays its own timeline:timeline.addTween(createjs.Tween.get(shape).to({x: 100}, 10))in frames, with labels,_offand frame actions (Tween.get(this).call(...)), as exported clips are written. - Filters and effects.
filterswithBlurFilter,ColorFilter,ColorMatrixFilter(andColorMatrixwithadjustBrightness,adjustContrast,adjustSaturationandadjustHue) andAlphaMaskFilter, shown once the object is cached, as CreateJS shows them:cache(x, y, width, height, scale),updateCache()anduncache().shadow(new createjs.Shadow(color, x, y, blur)),maskwith a shape, andcompositeOperationas a blend mode ("multiply","screen","lighter","overlay","darken","lighten","difference","hard-light","destination-out"). console.log()andalert()write to the Output panel, astrace()does.
A cached object is drawn as it is, not as it was when cached, so updateCache() is not needed to show changes, and drawing over a cache (updateCache("source-over")) is not there yet; text drawn as an outline is filled, and dashed lines are solid. What Test Movie does not have yet, such as createjs.DOMElement, drawing to a canvas's context, or another compositeOperation, says so in the Output panel when a script asks for it: that script stops there, and the movie plays on. A script that runs for more than five seconds (a loop that never ends) is stopped the same way.
What games use
In both versions:
- Text fields. A dynamic or input text field with an instance name is reached by it, and
score_txt.text = "Score: " + scorechanges what it shows, in its own font and color. A field that names a variable (ActionScript 1 and 2) shows the variable's value as it changes, and typing into such an input field sets the variable. - Typing. Click an input field, or focus it from a script, and type: the text goes in at the end, Backspace takes off the last character, and Enter starts a new line in a multiline field.
- Dragging.
startDrag()andstopDrag(), with a lock to the center and bounds, as a function or on a clip;_droptarget(ordropTarget) says where it was let go. - Hit tests.
hitTest(x, y, shapeFlag)andhitTest(otherClip), andhitTestPointandhitTestObject; with the shape flag, the clip's art counts rather than its box. - Clips from the library.
attachMovie("linkage", "name", depth, {_x: 10}),duplicateMovieClip()andremoveMovieClip(), for symbols exported for ActionScript. - Sound. Sounds placed on keyframes play as the frames are reached, as their sync and loop settings say. Library sounds exported for ActionScript play from scripts:
new Sound()withattachSound("linkage"),start(seconds, loops),stop()andsetVolume(), or a sound's class withplay();stopAllSounds()andSoundMixer.stopAll()silence them. getTimer()counts the milliseconds since the movie started, andgetURL()opens web links in your browser.
Errors and trace
What scripts trace() goes to the Output panel (F2). A script error stops that script only, and is shown in the Output panel, in red, with the frame or button and the line it was on, and in ActionScript 3 the functions it was in; the movie plays on, and the line below the movie counts the errors.
Once the Test Movie window is closed, double-click an error in the Output panel to see its script in the Actions panel with the caret on that line.
To check a movie's scripts without a window, for a whole folder of games say, use Phoenix play on the command line: it plays the movie, prints what its scripts trace and the errors they stop on, and can click every button in turn.
Simple frame actions while animating
Playback on the stage, and exported movies, do not run scripts. With on, they follow the simple calls in frame scripts (stop(), play() and the gotos), which is enough for a pose held or a section repeated; see Frame scripts.
Loading other movies (SWF files), video, the microphone and camera, sockets, ByteArray's readObject and writeObject, and the DataGrid, TileList, ScrollPane, UILoader and ProgressBar components. Published SWF files carry their ActionScript compiled, ActionScript 3 with the same classes Test Movie loads (see SWF movies).