Animation basics of ActionScript 3.0-3

Source: Internet
Author: User
Author: egoldy nature: Translation Views: 11624 published at: 15:14:42

Statement: This article is an example of the Chinese version of the unpublished Keith Peters event 3.0 making things move. The second chapter in the book. Webstudio will provide forum Forum support when publishing the Chinese version. Please indicate the source for reprinting. Thank you!


Next to the previous article .....

2.5 use code Animation 

Well, now you should have understood enough basic knowledge about how to encode in as3. You have selected a development environment and you are ready to start. Next, let's dive into some ActionScript animation content.

2.5.1 Loop 

Almost all animation codes contain loops. If you think of a frame-by-frame animation, you may need a process, which will be a series of Bitmap-like content. Each frame is an image and only needs to be displayed, for example, 2-3.


Figure 2-3. frame-by-frame animation

When you enter a graphic or Component symbol in flash, the situation may be somewhat different. Flash cannot create or save a new image for each frame, even in a frame-by-frame animation. On each frame, flash stores the position, size, color, and so on of each object on the stage. Because, if you have a ball that passes through the screen, each frame will save the position of the ball on the current frame. The first frame of the ball may be 10 pixels away from the left, and the second frame may be 15 pixels. The Flash Player reads the data, sets the stage according to the description, and displays the frame. Based on this, you can get another extended process, as shown in 2-4.
But when you think about how to describe a dynamic, actionscript animation, its flow looks like this. 2-5.


Figure 2-5. Script Animation

As shown in Figure 2-5, there is no concept of the first frame or the second frame. Generally, you can do the following operations on an ActionScript animation, which only occurs on one frame. Here you can start to understand the loop that I'm talking about.
First, you can set an initialization status. You can drag a video clip to the stage, just as you want to create a compensation animation. Or you can use only the code to describe the entire scenario. Either way, you need to render and display frames.
Next, apply your rules. This rule can be simplified to "this ball moves 5 pixels to the right," or they can use a complicated triangle to make many lines. The examples in this book will cover these scopes.
The application rule will get a new State-a new rendered and displayed description. Then, the same rules are repeatedly applied.
Note that the same group of rules are used repeatedly. You do not need to set a group of rules for the first frame, and then set another group of Rules for the second frame. Therefore, you need to set a set of rules for your task to handle all possible situations in your scenario. What should I do when the ball moves the right side quickly and moves out of the screen? Your rules need to be filtered out. Do you allow users to interact with these balls with the mouse? Your rules also need to be filtered in.
It seems a little scary, but in fact it is not really so complicated. Basically, you can create some very simple behaviors using one or two rules. When they work normally, you can add other rules.

The "Rules" rules mentioned here, which I have always called, actually refer to The ActionScript declaration. Each rule can be a single declaration, several combinations, or many declarations. In this example, the small ball moves 5 pixels to the right, and its rules look as follows:

ball.x  =  ball.x  +  5;

You just pointed out the X position of the ball (horizontal direction) and increased by 5 to generate a new X position. You can write the following code in a simpler way:

ball.x  +=  5;

The + = Operator only adds the value on the right to the variable on the left. And specify the result to the variable.
The following is the application of a group of rules that are slightly more advanced in this book. You will see later in the book:

var  dx:Number  =  mouseX  -  ball.x;var  dy:Number  =  mouseY  -  ball.y;var  ax:Number  =  dx  *  spring;var  ay:Number  =  dy  *  spring;vx  +=  ax;vy  +=  ay;vy  +=  gravity;vx  *=  friction;vy  *=  friction;ball.x  +=  vx;ball.y  +=  vy;graphics.clear();graphics.lineStyle(1);graphics.moveTo(ball.x,  ball.y);graphics.lineTo(mouseX,  mouseY); 

Don't worry about what they mean, as long as you know that flash will need to run such code to generate every new frame.
So how do you make them run cyclically? I will show you my first attempt. It will also be an error that many beginners may encounter. It is based on the basic loop architecture in almost all programming languages, such as for and while. You can use one of these architectures to set loops, which will repeat code execution in its content. This is what I did:

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

It looks very simple. The initial value of variable I is 0, and the clip of a small ball is placed on the stage at the X axis 0. I ++ will increase the variable I by 1 every time in a loop, from 0 to 1 to 2, 3, 4, and so on. The value is assigned to ball every execution. X to move it from the left and right of the stage to the right. When I reaches 500, the declaration of I <500 changes to false, and the loop stops.
If you make the same mistake, you may know that the ball will not pass through the stage-it is simply displayed on the right side. Why is there no intermediate moving process? Okay, actually it did! You just didn't see it, because you never asked flash to update the screen. Figure 2-6 shows the nature of the process.


Figure 2-6. Why can't you use for animation?

You have applied the rules and moved the positions of the ball to create 500 new scenarios. But it is not displayed until the loop ends. This is because Flash only updates the scenario at the last frame. This is very important.
Here is the sequence of actions executed for each frame:
1. Place the positions of all objects on the stage, including any level, any layer, loading video clips, and so on.
2. Execute all the ActionScript to be called on that frame, including any video clips or buttons at any layer or level, or nested video clips at any depth.
3. check whether there is time to display frames. If you set the frame rate to 20 frames per second, flash checks whether a frame can be displayed at least 50 milliseconds. If possible, it will display the rendered frame and move it to the next frame. If not, it will wait until the correct amount of time passes.
You need to know some questions about time. First, the frame frequency is always inaccurate (even the current Flash Player 9 video ). Don't expect them to have a strict and accurate time. Second, it is likely that the rendering or ActionScript execution time exceeds the time allocated to each frame. You don't have to worry that your script will be cropped, and Flash will execute the script before moving it to Step 3 (Part 2), although it will be slower than the frame frequency. Flash will actually wait 15 seconds for the script to be completed on the specified frame. It will display a line of prompts "a script causes the player to run slowly ......" .
In the previous example, before entering the next frame, flash waits for the end of the For Loop and updates the screen only before the next frame. That's why you only see one jump, not a move.
Therefore, all you need to do is to break this loop through frames, so you need to go back to the process shown in 2-5.

2.5.2 frame loop 

Because this book is not about processing the timeline and content on a single frame, I don't plan to give an exact frame loop example. Here, I just described this concept. If you are using Flash CS3 IDE, it may be a very practical example for you to start from.
When talking about the frame loop idea, we should go back to the flash of earlier versions. At that time, the ActionScript was not as powerful as today. The idea is to place some code on a specified frame, and then put a statement on another frame, usually gotoandplay, which allows the playback header to return to the previous frame. In this way, an infinite loop is formed between two frames. Every time the playback header is played to a frame with a code generation, the code on the frame will be executed.
It is important to note that there are two frames, the code is executed, the screen is updated and displayed, and the playback header is moved. In this way, the screen will be refreshed every time the Code is repeatedly executed, and you will get an animation.
For example, you have a video clip named ball on your stage. Then the code on the first frame should be like this:

ball.x  ++;

The code for the second frame is as follows:

gotoAndPlay(1);

In fact, in this example, there can be nothing in the second frame, because the time will be automatically played back by default.
As a transformation to this example, you can set it to three frames. The first frame is an initialization frame. You can place any code that runs only once on it, rather than a loop. The second frame will include the main action, and the third frame will be gotoandplay (2 );
The first frame may set the initialization position of the ball, change the color or size of the ball, or do anything else only once. The timeline will have no research cycle between 2nd frames and 3rd frames, motion animation and update screen.
In the early Flash 5 or earlier versions, this method was widely used. Although it is not popular, it still works very effectively. Even so, you will soon find a more flexible and powerful setting method, which is very instructive. You can see different aspects of the video-initialization, action, and loop-these concepts will continue to be used after you learn about every animation setting process.

2.5.3 clip events) 

We are glad that the clip event has been completely removed from as3, but it still deserves our attention as a footer. Back to the Flash 5 period, the clip event is the most important choice for frame loops.
Clip events refers to the stored code. Instead of putting the code on the time line, clip events directly places the code on the video editing itself. The method is to select a video clip on the stage and open the ActionScript panel. After opening the panel, enter your code on the ActionScript panel. When you do this and enter code on the ActionScript panel, the code is directly assigned to the video clip.
I said the code was added to the video clip "(" On "). Any and all code is in a clip and displayed in the clip Event code block. It looks like this:

Onclipevent (eventname) {// code written here}

In addition to onclipevent (eventname), there is also on (eventname), this "on" event also acts on mouse and keyboard actions, such as press and release ).
An event name is one of many events that may occur in a flash video. An event can be simply described as something happening in a video. Events can be divided into two categories: system events and user events. A system event occurs when something occurs in a computer, Flash, or your video, such as data loading, content loading, or a new frame is playing. A user event is something that the user has done, usually a keyboard or mouse activity.
The most common types of editing events are load and enterframe. The load event occurs when a video clip instance appears on the stage for the first time and any instance runs only once. You just need to put your code in two parentheses:

Onclipevent (load) {// initialization code}

The enterframe event occurs every time Flash is prepared to enable the rendering of the next frame, even if there is only one frame of the video. For example, if the frame frequency is set to 20 frames per second, enterframe will run around once every 50 Hao seconds. This enterframe editing event is where you often apply "rules" or action code, because you have two requirements: repeated code and re-display after each execution. It looks as follows:

Onclipevent (enterframe) {// Action Code}

In this way, you place a video clip on the timeline and add the following code (note that this is the early as 1 syntax ):

onClipEvent(load){this._x  =  100;this._y  =  100;}onClipEvent(enterFrame){this._x  +=  5;} 

In addition, the examples in this book do not use this setting method (because it is not part of the as3 language), but there are three main points to note: initialization, repeated actions, and screen refreshing, it will be part of any animation you make in any system.

2.5.4 events and event handlers) 

Flash MX has introduced many important changes in ActionScript-the biggest change and improvement is to bring flash into the frontier of rich application development. One of the biggest changes is the new event architecture, which can make more complex applications than previous versions.
I have already introduced some content about the event. It occurs when something happens in the system or the user does something through the keyboard and mouse. Before Flash MX, the only way is to capture events through the onclipevent (eventname) or the on (eventname) code block on the video clip and button. This means you have to place a video clip on the stage during creation and write code on it. Although methods have been explored, none of them are ideal. The MX event architecture cannot be the best, but compared with the previous version, it has a great improvement and allows you to access events from any location in the program, you can stop a specified event at any time or dynamically change the behavior of an event. You can imagine
How powerful and flexible it is.
With the advent of Flash MX 2004, a component framework is added to the event architecture to improve the event performance. However, this enhancement is implemented only by adding as2 classes based on the original event architecture. These classes provide many additional event operations. In some cases, the functions provided by as2 are still insufficient at the underlying layer of the event architecture.
In as3, the event architecture has been rewritten from the bottom layer. It is fast, powerful, and fully integrated with Flash Player.
To understand events, you need to understand the other two concepts: Listeners and handlers ). Listeners and processors are really good names, because that is what they do. A listener (listener) is an object that listens for events. A handler is a function that processes events when an event occurs. The listener and handler are very different in their execution throughout the history of ActionScript, and they are even different in as2. To avoid confusion, I will explain as 3 directly. In as3, it will be more pure, more beautiful and coordinated throughout the system.

2.5.5 listeners and handlers) 

Generally, a listener is an object that listens for events. You can call the addeventlistener function to specify your class as a listener to listen for the specified event. You need to pass the name of the event to be listened on and the name of the function to be processed in the class. The following is an example:
Addeventlistener ("enterframe", onenterframe );
You can add other additional parameters when adding event listeners, but we didn't do this in this book. The above syntax is required in most event applications.
Note that the event name, "enterframe", is a string that we all know and is also a magical string. Why is it amazing? If you accidentally write it into "entorframe", the compiler will not display any prompts to magically accept it, even if there is no such event name, then you will spend several hours solving a magical question, that is why your event function is not called.
However, as3. You can use the properties of the event class instead of using magic strings like "enterframe. For example, in the above example, you can write as follows:

addEventListener(Event.ENTER_FRAME,  onEnterFrame);

If you check the attribute value of event. enter_frame, you will find that it is actually a simple string "enterframe ". Now, you may think that this method is also very easy to write as event. entor_frame. However, the improvement here is that if you write an error, your program will reject compilation and will correctly tell you that there is no such attribute in the event class. It not only accurately indicates the number of rows in which you are wrong, but also the words in this line. It can be said that it cannot be better, unless one day the compiler can change your errors and write code for you.
In addition to the event type, there are other event types in other classes, such as mouseevent. mouse_down, keyboardevent. key_down, timerevent. timer, and so on. They are all equivalent to simple strings such as "mousedown", "keydown", and "timer". The best way is to forget these strings and use only attributes.
In the next example, you can directly call the addeventlistener function in a class. In this example, you actually sued this class for listening to its own enterframe events. In some cases, you want to listen to events generated by other objects. For example, if you have a Sprite named myspritebutton, use it as a button. When a user clicks this Sprite, it generates a mousedown event. To listen to the mousedown event from this Sprite, you need to call the addeventlistener method of that Sprite, as shown below:

mySpriteButton.addEventListener(MouseEvent.MOUSE_DOWN,  onSpritePress);

The last thing to note is that it is not like the previous version of the event handler. You must use the specified event handler function name, such as onenterframe. When you add a listener to as3, you can name your event handler with any name. In the enterframe example, I use onenterframe as a handler only because it is suitable for me and is used to using it like this. In as3, The onenterframe is no longer fixed. I can name the enterframe handler as move, run, or dosomethingcoll at will. However, according to the Convention, the event processing function usually starts with on, followed by the description of the event and where it may come from, such
Onstartbuttonclick, onconfigxmlload, or onrocketcrash. Some people also like to add the handler suffix after the event name as the name of the event processing function-for example, enterframehandler. So, this is just a matter of preference. The most important thing is to maintain consistency. As long as you can see it, you will know it is an event processing function.

Now I have explained the listener for the event, but there may be more accurate descriptions of the listener (listener): the event to be notified. Internally, the objects that generate events are saved as a list, and each object has been added as a listener. If an object can generate different types of events, such as mousedown, mouseup, and mousemove, it will save a list of listeners for each event type it can generate. No matter when an event occurs, the object will run again in the corresponding list and let every object in the list know what event has happened.
Another way to describe an event is to say that the object that becomes a listener is committing a specified action. At the same time, the object that generates the event is broadcasting the event to all the submitter.
In addition, if you do not want an object to listen to an event, you can tell it to stop listening or commit by calling the removeeventlistener method:

removeEventListener(Event.ENTER_FRAME,  onEnterFrame); 

This means that the listener is removed from the listener list that tells the object to listen for the specified event, so it will not receive any other notifications.
Let's continue to look at some specific applications. The following code creates a new Sprite, puts it on the stage, draws some graphics inside it, and then adds an event listener. Starting with the basic program framework, add the following code:

package  {import  flash.display.Sprite;import  flash.events.MouseEvent;public  class  EventDemo  extends  Sprite  {private  var  eventSprite:Sprite;public  function  EventDemo()  {init();}private  function  init():void  {eventSprite  =  new  Sprite();addChild(eventSprite);eventSprite.graphics.beginFill(0xff0000);eventSprite.graphics.drawCircle(0,  0,  100);eventSprite.graphics.endFill();eventSprite.x  =  stage.stageWidth  /  2;eventSprite.y  =  stage.stageHeight  /  2;eventSprite.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);eventSprite.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);}private  function  onMouseDown(event:MouseEvent):void  {trace("mouse  down");}private  function  onMouseUp(event:MouseEvent):void  {trace("mouse  up");}}} 

How can this problem be solved? The main function of the init function is to create a Sprite, draw a circle in it, and then align it to the center of the stage. The heaviest is the last two rows. This class adds itself as a listener to listen for two events: mouse_down and mouse_up. Note that they are attributes of the mouseevent class. The mouseevent class must be imported first. As a handler (handlers, also known as a handle), you pass in the onmousedown and onmouseup functions, they will be placed behind. Handler generally receives an object that contains event information. In short, it will include information about the event triggered by some objects. In this example, the mouse event includes the cursor position when the event occurs.
Set, which mouse button is pressed, and so on. For a keyboard event, it includes the key that is pressed during the event; the status of other keys, such as Ctrl, ALT, and shift. You can refer to the Help file to view information about various event types.
Save the above example as eventdemo. as file and use the compiling environment you selected to compile it, as described above, when you run SWF, you will see that every time you are in the new Sprite) when you press or open the mouse, the corresponding information is output on the output panel. If you are using Flex builder 2, do not forget to debug --- instead of running --- your program. If you are using a free SDK, use the correct TRACE method to solve the problem. Make sure that you can make it work normally. It is a very simple example, but it can be used to check whether your development environment is correctly configured.

If you have just got in touch with ActionScript and you have made it work and understood it, congratulations, you have risen from entry level to intermediate level.
Okay, now you know something about handlers. You can better understand listener ). As I said before, it is an object that produces a thing broadcast event or notifies its event listener. How is it done? Well, all it has to do is call the function of the object. The object must have the correct handler name. In the previous example, the eventdemo class added itself as a listener to listen on two sprite events. Internally, Sprite saves a list for each event. Then it has a list of mousedown events and a list of mouseup events. They may be just a simple array. Each list contains a reference to a primary video,
That is, an instance of the eventdemo class.
When a user clicks the mouse on the sprite, the sprite will respond, "Wow, click the mouse! It must pass the listener !" (Or something like this ). Then it will go to the mousedown list and check what is there. Sprite found a reference to the main film and a reference to the function specified as the handler. In this example, the function is called onmousedown. Then it simply calls the listener's function. If other objects are registered as listeners for the mousedown event, they will also be in the list and their defined handlers (handle) will also be called.
The same thing also happens when you move the mouse up, but they are in the mouseup list.
An important technology in as3 is that the maximum range of problems has been solved. This problem is complicated, but a simple method to understand where the event function is called at what time. Although as2 event architecture looks very similar to as3 on the surface, the class method in as2 must be called as an event function and executed only when it is a method of the called object. It is not an object defined in a class. If this seems confusing to you, this is the cause of the problem, and there is a whole class-delegate class-which is created to try to solve the problem. If this paragraph makes you feel boring, relaxed, and pleased, you don't need to think about it again in as3.
These are the basis of the event and event processing functions. We will continue to introduce some events with our progress, but now, let's go back to the animation.

2.5.6 animation events 

For example, where have we been taken by all the questions we talked about events? We are looking for a way to apply code to an animation object and refresh the Screen repeatedly. You have seen an example of using the clip event of enterframe for animation. Let's start with this technology.
In as3, you can add a listener (listener) to listen on enterframe events as follows:
Addeventlistener (event. enter_frame, onenterframe );
Remember that you need to first import the event class and create a real method named onenterframe.
One thing that will often confuse people is that when there is only one frame of a video, your enterframe event will still work normally. (And if you are using Flex builder 2 or SDK, you cannot see any frame, but it is indeed a fact that it exists) the playback header does not actually enter a new frame; it just stops at the first frame. Realize that the enterframe event does not move the playback header to a new frame. The most important thing is that the event tells flash when to move the playback header. You can think of enterframe as a timer, but it is not very accurate. Based on the frame frequency settings, flash checks the number of frames to be transferred to a new frame at intervals. Then it will execute the event repeatedly inside. If there are other
The frame can be played to it. Another point is that you can calculate the number of repeated event executions.
Original book p36
(If you are very interested in the internal working process of flash, you can view the tinic Uro blog at www.kaourantin.net. Tinic is a Flash Player Development engineer working in Adobe. It often provides some in-depth explanations on how the flash scenario works .)
The initialization code already exists in the previous example, either an initialization frame or an onclipevent (load) code block. You may have guessed that all these code generations can occur in the init method. The init method can only be called once by the constructor. You need to get used to the init method and won't be called twice in your video. If you need to reinitialize some variables or call other methods, place them in other functions and call them as needed.
The following is our first as3-based animation example!

package  {import  flash.display.Sprite;import  flash.events.Event;public  class  FirstAnimation  extends  Sprite  {private  var  ball:Sprite;public  function  FirstAnimation()  {init();}private  function  init():void  {ball  =  new  Sprite();addChild(ball);ball.graphics.beginFill(0xff0000);ball.graphics.drawCircle(0,  0,  40);ball.graphics.endFill();ball.x  =  20;ball.y  =  stage.stageHeight  /  2;ball.addEventListener(Event.ENTER_FRAME,  onEnterFrame);}private  function  onEnterFrame(event:Event):void  {ball.x++;}}} 

The init function creates a Sprite named ball and sets the event listener. The onenterframe function is used to implement animation, move the ball, and then the screen will be refreshed. It is not very complex, but it is the basis of all other content in this book, so it should be well understood.
Well, we have already covered a lot of content about how to structure the ActionScript animation. Explains how to apply rules to repeatedly run, and how to update the screen after applying the program rules to create a motion illusion. But what can you use it to move? So far, you can move a Sprite, but all the current code is simply applied to a video clip. Next, we will study how to create a Sprite and shadow clip and use the display list to use the display.

To be continued

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.