Week 6: Animating With Code

Topics

  • Frame-based events
  • Timers
  • Hit Testing

So far we’ve been working with user-generated Mouse Events. Today we’re going to explore some non-User events that allow us to animate and react with code.

>>Week 6 Examples

Frame-based Events

Now that we are comfortable with working with and creating display objects, and using event listeners and event handlers, we can also create animation entirely from code, without involving the timeline. To do this, we use a new event type, onEnterFrame, or ENTER_FRAME event.

You might think that you could use a for loop for animation, like this:

for(i = 0; i < 500; i++){
    ball.x = i;
}

Where “ball” is a display object that you have defined elsewhere. You might think that this code would move the ball 1 pixel 500 times, and in a sense you would be right. The problem is that you would only see the result of the last loop, because all 500 loops are executed before the frame is rendered.

To get around this, you need to introduce time between loops, which is where ENTER_FRAME comes in. The ENTER_FRAME event is dispatched at the frame rate of the .swf.

This is how you set up an enter frame event:

instancename.addEventListener(Event.ENTER_FRAME, eventHandler);

function eventHandler(event:Event):void {

            //do something
 }

Timer Events

You can also set up an event that will happen at regular intervals in your code. This is called a Timer Event. A timer is actually an object, so first you need to create a new Timer instance, then add an event listener and handler to it, and last, start the timer!

//create the timer instance
var myTimer:Timer = new Timer(500, 10);

//add the timer event to it
myTimer.addEventListener(TimerEvent.TIMER, eventHandler);

//start the time
myTimer.start();

function eventHandler(event:TimerEvent):void {
    //do something
}

Hit Testing

It can be useful when creating dynamic code based animation to be able to detect when one display object collides with another. This is called “Hit Testing”. You can hit test two ways, with two objects or with an object and a point on the stage.

To hit test two objects, use the hitTestObject method:

object1.hitTestObject(object2)

To hit test and object and a point, use the hitTestPoint method:

object.hitTestPoint(xcoordinate,ycoordinate)

 Homework

Simulate the game of Pong! Create an animation that uses enter frame to animate the properties of at least 3 objects and a hit test between them, and incorporates a timer.

Also, turn your drawing app homework in again with comments, so that I know you understand how it works!

Note: Next week we are going to have an in class quiz on the material we have covered so far. If there is anything you are unclear on, now is the time to ask questions. The quiz will be on paper, and you will not be allowed to look things up on the internet

 

Leave a Reply