11
time

animation

Event.ENTER_FRAME

one of the most used event properties in flash is probably Event.ENTER_FRAME. it executes as the flash player prepares to render the next frame to the screen, whether the playback head is moving through an animation or idling on a single frame.

code assigned to the enter frame property is generally used to update the screen to reflect the current state of the application.

import flash.events.Event;
function reportX(e:Event):void { trace(stage.mouseX); }
addEventListener(Event.ENTER_FRAME, reportX);

Timer

as an alternative to onEnterFrame which occurs once every frame, the Timer class can be used to schedule a function to be executed after an arbitrary length of time:
import flash.utils.Timer;
import flash.events.TimerEvent;

function reportX(e:TimerEvent):void { trace(stage.mouseX); }

var timer:Timer = new Timer(1000); // milliseconds
timer.addEventListener(TimerEvent.TIMER, reportX);
timer.start();

time-varying values

animation is nothing more than repeatedly drawing a scene with slight changes from one frame to the next. if we set up some inititial variables and modify them every so often from an Event.ENTER_FRAME or a TimerEvent.TIMER event listener, we'll have a simple animation:
import flash.display.Shape;
import flash.events.Event;

var r:Number = 50;
var shape:Shape = new Shape();

addChild(shape);
shape.graphics.beginFill(0x000000);
shape.graphics.drawRect(-r,-r, r+r,r+r);
shape.graphics.endFill();
shape.x = stage.stageWidth * .5;
shape.y = stage.stageHeight * .5;

function onFrame(e:Event):void {
   shape.rotation++;
}

addEventListener(Event.ENTER_FRAME, onFrame);
or maybe: strand [swf] [as] [fla]

 

accurate speed

if we base our animation on variables that are changed by the same amount every update event, we tie ourselves to a particular frame rate. this isn't always a problem, but if you've ever played a really old video game on a really new computer, you know that it can be, and the fix is very simple.

by looking at the amount of time elapsed since the last update, we can calculate exactly how far things should travel based on their speed. doing this frees us from any dependency on frame rate—our positioning will always be accurate, regardless of how many times we paint the screen per second.

[as] [fla]

structuring code for interactivity

in any situation where user input needs to modify visual output, the code will generally follow a similar pattern: storing the current state, rendering a visual representation of the current state, and processing input to modify the current state.

model the subject

create properties and methods that encode characteristics and functionality.

periodically render the current state

create a visual representation of the current state, either at a regular interval, or only when a visual update is required (state changes).

process input and modify state

listen for events and update state accordingly.