O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  


 
Buy the book!
Flash Hacks
By Sham Bhangal
June 2004
More Info

HACK
#27
Time-Controlled Movement
All scripted subanimations do not need to run at the frame rate. Make a subanimation run at a rate independent of the frame rate by using timed events
The Code
[Discuss (0) | Link to this hack]

The Code

The following code demonstrates the differences between and benefits of using setInterval( ) instead of an onEnterFrame( ) handler to update the animation. The code creates two movie clips and makes them move across the Stage in 1-pixel steps. The puck1 clip appears to move much more quickly and smoothly because it is being animated as fast as the Flash Player can run. The puck2 clip moves at the current frame rate, which will be 12 fps by default.

mover = function( ) {
  this._x += speed;
  if (this._x > 550) {
    clearInterval(this.interval);
  }
  updateAfterEvent( );
};

function enterFrameMover( ):Void {
  this._x += speed;
  if (this._x > 550) {
    delete this.onEnterFrame;
  }
}
function drawBall(clip:MovieClip, x:Number, y:Number):MovieClip {
  var mc:MovieClip = this.createEmptyMovieClip(clip.toString( ), 
                           this.getNextHighestDepth( ));
  mc.lineStyle(40, 0xCCCCCC, 100);
  mc.moveTo(-1, 0);
  mc.lineTo(1, 0);
  mc._x = x;
  mc._y = y;
  return mc;
}
var speed:Number = 1;
var puck1:MovieClip = drawBall(puck1, 20, 200);
var puck2:MovieClip = drawBall(puck2, 20, 300);
puck1.intervalMover = mover;
puck1.interval = setInterval(puck1, "intervalMover", 1);
puck2.onEnterFrame = enterFrameMover;

Note the way setInterval( ) is created:

  • The interval ID returned by setInterval( ) is of type Number.

  • The interval ID has to be known so that we can remove the interval to which it refers at the end of the animation. The interval ID could be passed as an argument, but in this case we add it as a timeline variable, interval, on the puck1 clip.

Of course, making the frame rate really high, such as 95 fps, would ensure that both movie clips moved quickly and smoothly, but that technique has two limitations. First, if all the animations are dependent on the frame rate, it is harder to vary the speed of different graphic elements. Second, if you try to make everything move too fast, the Flash Player won't be able to achieve the requested frame rate. The setInterval( ) technique allows you to selectively target the critical areas of your motion graphics that must run quickly . It is worth noting that if you make the whole SWF run faster, the maximum frame rate you can achieve is considerably less than if only portions run faster.


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.