In the last lesson, we got our company logo to come up on the screen. Today, we’re going to learn how to animate that logo, and we’ll also learn how Flash’s display lists work. Remember the UIComponent that we added last lesson? In Flash, Sprites, Graphics and MovieClips all extend from a base class called DisplayObject. DisplayObjects are items that are added to DisplayLists in order to appear on the screen. Flex’s canvas does not allow DisplayObjects to be added, so we add a UIComponent first, and then we can use its DisplayList to add all of our sprites. The DisplayList determines the front to back order (or z-order) of all the displayed objects.
There are many methods that you can use to handle the DisplayList, but we are going to focus on just 3 of them. addChild() is used to add a new DisplayObject to the end of the DisplayList. This places the object on top of the other objects on screen. If you’d like to add an object with a different z-order, you can use addChildAt() to place it in front of or behind any of the other DisplayObjects in the list. Finally, to remove an object from the screen, simply use removeChild(). To see all of the methods you can use, check out the DisplayObjectContainer class.
We’ll use these methods momentarily, but first let’s discuss animation. In the first lesson, we created a method called step() that is called every frame (30 frames per second). Let’s imagine that we wanted to move a ball 300 pixels every second. If we were to place ball.x += 10 in the step() method, it would work right? 10 * 30 is 300, so in a perfect world, that would be all the work required. Sadly, computers are not a perfect world. If your game was run on a slower computer, it may only be able to run at 18 frames per second. Then, your ball would only move 180 pixels. To avoid this, you simply need to take into account how much time has actually passed since the last frame was displayed. To get the current time in Flash, you can use the getTimer() method. This will return the number of milliseconds that have passed since the movie started. Now, the new version of step will look like this:
Click for the code