actionscript

tech2024-04-12  9

actionscript

The fads of Internet design may come and go, but one thing that will never change is that the more dynamic you make your Flash creations, the more engaging they are to the user. This dynamism can be counterproductive under certain circumstances, especially when multiple effects battle for the user’s attention, or the effects are too garish. Identifying the key to effective animation is like the search for the Holy Grail. What some users think is a cool effect, others find patently uninteresting – and vice versa. Never lose sight of the importance of striking a balance between the interface and the animations you’re attempting to produce.

互联网设计的风尚可以来来去去,但永远不变的一件事是,Flash创作的动态性越强,对用户的吸引力就越大。 这种动力在某些情况下可能适得其反,特别是当多种效果争夺用户的注意力,或者效果过于扎眼时。 确定有效动画的关键就像寻找圣杯。 一些用户认为很酷的效果,另一些用户则认为毫无意义,反之亦然。 永远不要忘记在界面和尝试制作的动画之间取得平衡的重要性。

Flash has always had as its nucleus animation and motion. This is, after all, what Flash was originally created for – the animation of objects over time. As new versions are released and the technology evolves, so do the capabilities of Flash’s scripting language. What we could once achieve only with keyframes and tweening can now be accomplished in a few lines of ActionScript. Some developers find this reality difficult to grasp, but as we saw in Chapter 2, Navigation Systems, once you understand the basics, you can build on them with new experiments.

Flash一直以动画和运动为核心。 毕竟,这就是Flash最初创建的目的–对象随时间的动画。 随着新版本的发布和技术的发展,Flash脚本语言的功能也在发展。 我们曾经只能用关键帧和补间实现的功能现在可以在几行ActionScript中完成。 一些开发人员发现很难理解这种现实,但是正如我们在第2章“导航系统”中所看到的那样,一旦您了解了基础知识,就可以通过新的实验在其基础上进行构建。

With very few exceptions, what can be done with keyframe tweening can also be achieved through ActionScript. But, what are the advantages of scripting? The answer’s simple: portability, scalability, and manageability. You can affect an animation dramatically by tweaking an equation or a few variables in its ActionScript. This process is much easier than laboriously editing motion tweens, which can sometimes appear in their hundreds in large animated effects.

除了极少数例外,关键帧补间可以通过ActionScript来完成。 但是,脚本编写的好处是什么? 答案很简单:可移植性,可伸缩性和可管理性。 您可以通过在ActionScript中调整方程式或一些变量来显着影响动画。 与费力地编辑补间动画相比,此过程要容易得多,补间动画有时会以数百个大型动画效果出现在补间动画中。

This doesn’t mean that motion tweening is dead, however – not by a long shot. If you create simple motion tweens (for example, an effect that shows an object increasing in size), then script the effect multiple times and experiment with it via ActionScript, you can create some pretty amazing effects with a minimum of effort.

但是,这并不意味着补间动画已经死了–远距离拍摄不是。 如果创建简单的补间动画(例如,一个显示对象尺寸增大的效果),然后对该效果进行多次脚本编写并通过ActionScript对其进行实验,则可以用最少的精力创建一些非常惊人的效果。

With Flash MX 2004, and the introduction of Timeline Effects, creating these motion tween building blocks takes even less work than it did before, as we’ll see in the coming chapter. I’ll give you the information you need to develop both classic effects you can be proud of and exciting new animations. You’ll also learn the techniques involved in creating innovative Timeline Effects. It’s virtually all ActionScript from here on, so have your calculator and pencil ready! And if you need a little review of the essentials of Flash, don’t miss Chapter 1 of this series.

随着Flash MX 2004的推出,以及时间轴效果的引入,创建这些补间动画构建块所需的工作比以前要少得多,正如我们将在下一章中看到的那样。 我将为您提供开发值得骄傲的经典效果和令人兴奋的新动画所需的信息。 您还将学习创建创新的时间轴效果所涉及的技术。 几乎所有ActionScript都是从这里开始的,因此请准备好计算器和铅笔! 而且,如果您需要稍微了解一下Flash的要点,请不要错过本系列的第1章 。

Note also that you can download this chapter in pdf format if you’d prefer to read the content offline.

另请注意,如果您希望离线阅读内容,则可以pdf格式下载本章 。

动画原理 (Animation Principles)

If you are reading this book, then I can be pretty sure you have a copy of Flash MX or later. You probably purchased Flash because of the animation capabilities that lie at its heart. In the most basic form of Flash animation, we can smoothly transition an object’s location or shape from point/shape A to point/shape B by altering the properties of that object at keyframes within the timeline. This used to be a cumbersome process in previous versions of Flash, but it’s more accessible now. With a solid understanding of ActionScript and the dynamics of motion you can rapidly create animation effects that would have taken many hours to create with previous versions.

如果您正在阅读本书,那么我可以肯定您拥有Flash MX或更高版本的副本。 您可能购买了Flash是因为其核心在于动画功能。 在Flash动画的最基本形式中,我们可以通过在时间轴内的关键帧处更改对象的属性,将对象的位置或形状从点/形状A平滑过渡到点/形状B。 在以前的Flash版本中,这曾经是一个繁琐的过程,但是现在可以更轻松地访问它了。 对ActionScript和运动的动态有深刻的了解,您可以快速创建动画效果,而使用以前的版本要花很多时间才能创建动画效果。

Hit the books!

打书!

What did you do with your old Physics and Math textbooks when you left school? Did you throw them away? Shame on you if you did – they can be an invaluable source of inspiration for creating mathematical and motion-related scripted animations in Flash. I’m a bit of a hoarder, which probably explains why I’ve still got mine!

离开学校后,您如何处理旧的物理和数学教科书? 你把它们扔掉了吗? 如果您这么做了,那就可耻了–它们是在Flash中创建数学和与运动相关的脚本动画的宝贵灵感来源。 我有点a积,这也许可以解释为什么我仍然有我的!

There are many uses for Flash in creating animation. Perhaps you want to create a straightforward animation that moves an object from point A to point B. Maybe you’re itching to build a more complex animation with a "real world" feel, easing objects into position or having them exhibit elastic characteristics. Both simple and advanced animations are possible in Flash via different methods: by hand, using complex keyframes and motion tweening, or with the help of ActionScript.

Flash在创建动画中有许多用途。 也许您想创建一个简单的动画来将对象从A点移动到B点。也许您想构建一个具有“真实世界”感觉的更复杂的动画,使对象放轻松或使其具有弹性特征。 在Flash中,可以通过不同的方法来制作简单动画和高级动画:手动,使用复杂的关键帧和补间动画,或者在ActionScript的帮助下。

While the ActionScript method of animation may initially appear difficult, once you become comfortable with its methodologies for movement and learn the nuances of its quick, effective methods, you’ll soon be creating increasingly complex animations and building on your existing knowledge. If this is your first experience with ActionScript, you’ll soon be surprised how easy it is to create scripted animation. This should inspire you to explore your own ideas and experiments, and take ActionScript to the limit.

尽管ActionScript动画方法最初可能看起来很困难,但是一旦您熟悉其运动方法并了解其快速有效的方法的细微差别,您将很快创建越来越复杂的动画并利用现有知识。 如果这是您第一次使用ActionScript,那么您很快就会感到惊讶,创建脚本动画是多么容易。 这应该激发您探索自己的想法和实验,并将ActionScript发挥到极限。

Animation Overload

动画超载

The ability to easily include animation techniques and effects within Flash movies is usually the reason people use this technology for animation development. However, inexperienced users may succumb to "animation rage," as they become a little too carried away with the power Flash puts at their fingertips. Over-the-top animation effects are the result – effects that, upon careless replication within the same movie, succeed only in creating an unpleasant experience, to say the very least!

在Flash电影中轻松包含动画技术和效果的能力通常是人们使用此技术进行动画开发的原因。 然而,没有经验的用户可能会屈从于“动漫愤怒,”因为他们成为与功耗Flash看跌期权在他们的指尖太得意忘形了一点点。 最终的结果就是动画效果–至少可以说,在同一部电影中粗心地复制时,效果只能成功创造令人不快的体验!

It’s easy to become trigger-happy and animate every element of your display, but this approach is a recipe for disaster. The effect that you set out to create will soon be lost, overwhelmed by all the others that surround it.

轻松触发并为显示的每个元素设置动画很容易,但是这种方法是灾难的秘诀。 您打算创建的效果很快就会消失,周围的所有其他对象将不知所措。

The key to an effective animation lies in maintaining a balance between the message you’re trying to convey and what’s happening on the screen. Even tipping the balance slightly can ruin your effect, so adopt the following guidelines as rules of thumb for creating successful animations:

有效动画的关键在于保持您要传达的消息与屏幕上发生的事情之间的平衡。 即使稍微增加平衡也会破坏效果,因此请遵循以下准则作为成功制作动画的经验法则:

Tame the Animation

驯服动画

"Because you can" is not a good enough reason to animate something. Users tend to identify excessive animation as the mark of the amateur – though your site will certainly make an impression, it won’t be a good one!

“因为您可以”不足以使某件事动起来。 用户倾向于将过多的动画标识为业余爱好者的标记-尽管您的网站肯定会给人留下深刻的印象,但这并不是一个好习惯!

Err on the Side of Subtlety

微妙的错误

Effects that are exaggerated or garish will annoy users, especially if the animation is part of the main interface or navigation. Strive to create effects that are pleasing to the eye, not intrusive.

夸张或夸张的效果会使用户烦恼,尤其是在动画是主界面或导航的一部分的情况下。 力求创造出令人愉悦的效果,而不是令人讨厌的效果。

Consider the User

考虑用户

Try to distance yourself from any effect you create; imagine you’re a user viewing it for the first time. If you think it’s "too much," then it probably is. If you don’t like it, your users won’t, either. Of course, you can’t please all of the people all of the time, so try to strike a happy medium at which most visitors will be satisfied.

设法使自己远离所产生的任何影响; 想象您是第一次查看它的用户。 如果您认为它“太多”,那么可能是。 如果您不喜欢它,那么您的用户也不会。 当然,您不可能一直都取悦所有人,因此请尝试以一种令人满意的媒介来满足大多数访问者的需求。

Stand back!

退后!

When previewing your movie, try standing several feet from the monitor. Believe it or not, this gives you a clear sense of the animation’s movement across the screen. If you’re too lazy to walk to the other side of the room, try squinting so that the screen blurs a little. You’ll be able to detect the movement on the screen without the distracting details, which will help you identify whether the movie is over-animated.

预览电影时,请尝试离监视器几英尺远。 信不信由你,这使您清楚地了解动画在屏幕上的移动。 如果您懒得走到房间的另一侧,请尝试斜视,以使屏幕略微模糊。 您将能够在屏幕上检测到运动,而不会分散注意力,这将有助于您确定影片是否动画过度。

Be Conservative with Animations

保守动画

Yes, you can create cool animations with ActionScript, but you shouldn’t include them all in one page, interface, or effect. You may lose focus by adding too many other animations to your design. Try to sprinkle animations through your designs, rather than deluging the user with an animation storm.

是的,您可以使用ActionScript创建酷炫的动画,但不应将它们全部包含在一页,界面或效果中。 通过在设计中添加太多其他动画,您可能会失去注意力。 尝试在设计中添加动画,而不是用动画风暴来迷惑用户。

补间还是不补间? (To Tween or Not to Tween?)

A few years ago, Flash developers had no choice. To create animated effects in Flash, we used keyframes and motion or shape tweening. Now, we have the luxury of choice; we can script the motion, or create it via the traditional route. Both methods deliver benefits, as we’ll see shortly, when we compare scripted animation with traditional tweening methods.

几年前,Flash开发人员别无选择。 为了在Flash中创建动画效果,我们使用了关键帧以及运动或形状补间。 现在,我们有很多选择。 我们可以编写动作脚本,或通过传统路线创建动作。 正如我们将很快看到的,当我们将脚本动画与传统补间方法进行比较时,这两种方法都具有好处。

One point worth noting, however, is that with motion scripting, the entire movie need not be any longer than a single frame. The ActionScript, not the timeline, controls the animation, allowing for well-organized movies with uncomplicated structures.

但是,值得注意的一点是,使用动作脚本编写时,整个电影的长度不必超过单个帧。 ActionScript(而不是时间轴)控制动画,从而允许组织结构简单,结构简单的电影。

Let’s take a look at a simple animation technique with which you might already be familiar: linear motion. The most basic effect that you can create is movement from one point to another and, indeed, this may have been one of the effects you tried when you first opened Flash. Let’s revisit it now.

让我们看一下您可能已经熟悉的一种简单的动画技术:线性运动。 您可以创建的最基本的效果是从一个点到另一个点的移动,实际上,这可能是您首次打开Flash时尝试过的效果之一。 现在让我们重温一下。

时间轴动画示例 (Timeline Animation Example)

It’s easy to create this effect on the timeline. Let’s walk through the steps involved.

在时间轴上创建此效果很容易。 让我们逐步完成所涉及的步骤。

Draw a simple shape (like a circle) on the stage and convert it to a movie clip symbol named Timeline_Animation. Position the symbol instance on the stage at (0, 0).

在舞台上绘制一个简单的形状(如圆形),并将其转换为名为Timeline_Animation的影片剪辑元件。 将元件实例放置在舞台上的(0,0)处。

Select frame 10 within the main timeline, right-click, and select Insert KeyFrame (F6). Notice that the movie clip instance is copied into the new keyframe.

在主时间轴中选择第10帧,单击鼠标右键,然后选择“插入关键帧(F6)”。 请注意,影片剪辑实例已复制到新的关键帧中。 Select the instance of the movie clip in frame 10, and move it to (100, 100).

在第10帧中选择影片剪辑的实例,然后将其移动到(100,100)。 Select frame 1, right-click, and select Create Motion Tween.

选择第1帧,单击鼠标右键,然后选择“创建补间动画”。

Preview your movie. You’ve created a simple animation that moves your clip from one point to another. This is a simple animation; if the effect were more complicated, the timeline could quickly become messy and difficult to work with.

预览电影。 您已经创建了一个简单的动画,将剪辑从一个点移动到另一个点。 这是一个简单的动画; 如果影响更为复杂,时间轴可能很快就会变得混乱并且难以使用。

Creating simple motion using the timeline in this manner can also be accomplished within Flash MX 2004 and later versions via Timeline Effects (more on this in Chapter 4, Text Effects).

以这种方式使用时间轴创建简单的动作,也可以在Flash MX 2004和更高版本中通过时间轴效果来完成(有关更多信息,请参见第4章,文本效果)。

ActionScript动画示例 (ActionScripted Animation Example)

Let’s take another look at this animation, but this time, let’s build it in ActionScript.

让我们再看一下该动画,但这一次,让我们在ActionScript中构建它。

Draw a simple shape (like a circle) on the stage and convert it to a movie clip symbol named Scripted_Animation. Position the symbol instance on the stage at (0, 0), and name the instance scripted_animation.

在舞台上绘制一个简单的形状(如圆形),并将其转换为名为Scripted_Animation的影片剪辑元件。 将符号实例放在舞台上的(0,0)处,并将实例命名为scripted_animation 。

With the Actions Panel open and the first frame of the main timeline selected, add the following code:

打开“动作面板”并选择主时间轴的第一帧,添加以下代码: var endX = scripted_animation._x + 100; var endY = scripted_animation._y + 100; var stepX = (endX - scripted_animation._x) / 10; var stepY = (endY - scripted_animation._y) / 10; scripted_animation.onEnterFrame = function () {  if (this._x < endX) this._x += stepX;  if (this._y < endY) this._y += stepY; };

First, we set variables for the x and y endpoints (endX and endY) to equal the starting coordinates plus 100 pixels along each axis. We then use these values to calculate how much the object will have to move per frame along each axis (stepX and stepY) to reach its destination in ten frames. We then introduce an event handler that moves the object along the two axes by the calculated distances until it reaches its destination.

首先,我们将x和y端点( endX和endY )的变量设置为等于起始坐标加上沿每个轴的100个像素。 然后,我们使用这些值来计算对象必须在十帧内沿每个轴( stepX和stepY )移动多少才能到达其目的地。 然后,我们引入事件处理程序,该事件处理程序使对象沿着两个轴移动计算出的距离,直到到达目的地为止。

This code takes the previous example a step further, though, because you can place this movie clip anywhere on the stage. Regardless of its starting location, the clip will move 100 pixels along each axis from its starting position.

但是,此代码使上一个示例更进一步,因为您可以将此影片剪辑放置在舞台上的任何位置。 无论其开始位置如何,剪辑都将从其开始位置沿每个轴移动100个像素。

You may be looking for more code to complete the effect, but that’s it! Simple, isn’t it? Of course, ActionScript becomes more complicated as you add more interesting effects, but this method certainly saves a lot of clutter on the timeline.

您可能正在寻找更多代码来完成效果,仅此而已! 很简单,不是吗? 当然,当您添加更多有趣的效果时,ActionScript会变得更加复杂,但是此方法无疑可以节省时间上的混乱情况。

Animations built using the timeline and motion tweening are useful for testing and for implementation as part of a larger animation (for example, creating simple rotation for a loading animation). The real benefits of developing animations with ActionScript are scalability and the opportunity for dynamic movement in response to user input or other variables.

使用时间轴和补间动画构建的动画对于测试和作为较大动画的一部分实现(例如,为加载动画创建简单的旋转)非常有用。 使用ActionScript开发动画的真正好处是可伸缩性以及响应用户输入或其他变量进行动态移动的机会。

Once you start animating with ActionScript, it’s difficult to stop – this method really does act as a springboard for your creativity. And, don’t forget to save your experimental FLA files even if you don’t use them straight away. You never know when you might need them!

一旦开始使用ActionScript制作动画,就很难停止–这种方法确实可以充当您创造力的跳板。 而且,即使您不立即使用实验FLA文件,也不要忘记保存它们。 您永远不知道何时需要它们!

创建功能库 (Creating Function Libraries)

Once the ActionScript bug has bitten you, you’ll be infected permanently, and there’s no known antidote! You’ll create many FLAs over time, and will no doubt build up your own core set of scripts and methods. But, rather than reinventing the wheel every time you need to carry out a particular function, why not save your scripts in .as (ActionScript) files? These files can then be included dynamically in your creations as you need them.

一旦ActionScript错误咬伤了您,您将被永久感染,并且没有已知的解毒剂! 随着时间的推移,您将创建许多FLA,并且无疑会构建自己的核心脚本和方法集。 但是,为什么不将脚本保存在.as (ActionScript)文件中,而不是每次都需要执行特定功能时就浪费时间呢? 然后,可以根据需要将这些文件动态包含在您的作品中。

I maintain a core of scripts that I’ve created over the past few years, and which I back up regularly. I’m always careful to sort my ActionScript files into a logical folder structure. That way, when I start a new project, I can go and grab my existing script files without any hassle.

我保留了过去几年创建的脚本核心,并定期对其进行备份。 我总是小心地将ActionScript文件排序为逻辑文件夹结构。 这样,当我开始一个新项目时,我可以轻松地获取现有的脚本文件。

Any scripts that are still in development, or that I haven’t had time to finish, I place in a file called unfinished.as. This way, I don’t lose the code or accidentally delete it, and I can come back to it later to finish or develop it further.

任何仍在开发中的脚本,或者我没有时间完成的脚本,都放在一个名为unfinished.as的文件中。 这样,我不会丢失代码或意外删除它,以后我可以返回它来完成或进一步开发它。

Hotmail for Backups

备份Hotmail

If I lost all of my code snippets, I’d be very unhappy! And, even though I perform regular backups, I can never be sure of their integrity. For this reason, I set up a free mail account with Hotmail, and created an archive folder. Now, every month, I mail myself a ZIP archive of my .as files. This may seem a little extreme, but if you’ve ever lost your work in a hard drive or backup failure, you’ll understand why I go to such lengths to protect my code.

如果我丢失了所有代码段,我将非常不高兴! 而且,即使我执行常规备份,也无法确定其完整性。 因此,我使用Hotmail设置了一个免费的邮件帐户,并创建了一个存档文件夹。 现在,每个月,我都会邮寄自己的.as文件的ZIP存档。 这似乎有些极端,但是如果您在硬盘驱动器上工作丢失或备份失败,您将理解为什么我会竭尽全力保护我的代码。

创建一个简单的函数库 (Creating a Simple Function Library)

A simple animation library can help you clean up your timeline and make things more manageable. To create your own library, follow these steps, or simply locate Simple_Motion.fla and Simple_Motion.as in the code archive:

一个简单的动画库可以帮助您清理时间线并使内容更易于管理。 要创建自己的库,请按照下列步骤操作,或在代码档案库中简单地找到Simple_Motion.fla和Simple_Motion.as :

Look at the code from the ActionScript animation example you completed above; specifically, look at the onEnterFrame event handler. We can write a function that does the same job for a specified clip, given stepX, stepY, endX, and endY values:

查看上面完成的ActionScript动画示例中的代码; 具体来说,请看onEnterFrame事件处理程序。 给定stepX , stepY , endX和endY值,我们可以编写一个对指定clip执行相同工作的函数:

Example 3.1. Simple_Motion.as

示例3.1 Simple_Motion.as

function SimpleMovement (stepX, stepY, endX, endY, clip) {  if (clip._x < endX) clip._x += stepX;  if (clip._y < endY) clip._y += stepY; }

The structure of the SimpleMovement function is similar to the event handler, except that it accepts parameters to tell it exactly what to do (and what clip to do it to), instead of relying on predefined variables.

SimpleMovement函数的结构类似于事件处理程序,不同之处在于它接受参数以确切地告诉它要执行的操作(以及要执行的剪辑),而不是依赖于预定义的变量。

Type the code for this function into a text editor (e.g., Notepad on PC, or BBEdit on Mac) and save it as Simple_Motion.as.

在文本编辑器中键入此功能的代码(例如,在PC上为记事本,在Mac上为BBEdit),然后将其另存为Simple_Motion.as 。

To use this file, add the following line of ActionScript to the root of any movie, in the first frame

要使用此文件,请在第一帧中将以下ActionScript行添加到任何电影的根目录中

Example 3.2. Simple_Motion.fla Actions : 1 (excerpt)

示例3.2 Simple_Motion.fla操作:1(节选)

#include "Simple_Motion.as"

This compiles the code from the Simple_Motion.as file into the SWF file when it is created, providing access to the SimpleMovement function we created above.

创建代码时, Simple_Motion.as代码从Simple_Motion.as文件编译为SWF文件,从而提供对我们上面创建的SimpleMovement函数的访问。

Alter the onEnterFrame event handler to use the imported function as follows:

更改onEnterFrame事件处理程序以使用导入的函数,如下所示:

Example 3.3. Simple_Motion.fla Actions : 1 (excerpt)

示例3.3 Simple_Motion.fla操作:1(节选)

scripted_animation.onEnterFrame = function () {  SimpleMovement(stepX, stepY, endX, EndY, this); };

Here, we’ve created a simple function call, passing the four variables defined on the root of the timeline, as well as the movie clip we wish to animate.

在这里,我们创建了一个简单的函数调用,传递了在时间轴的根部定义的四个变量以及希望制作动画的影片剪辑。

Preview you movie in Flash, and you’ll see it works exactly as before.

在Flash中预览电影,您将看到它与以前完全一样。

Including the function in another project is as simple as saving the .as file to the directory containing the FLA you’re working on, and adding the #include directive to the project. You can then use the function as often as you like.

将功能包括在另一个项目中非常简单,只需将.as文件保存到包含您正在使用的FLA的目录中,然后将#include指令添加到该项目中。 然后,您可以随意使用该功能。

创建主库 (Creating Master Libraries)

When you’re working on a series of projects that share a similar theme, you may find they also share bitmaps and vector and sound objects. If you’ve forgotten which FLA these shared objects reside in, you’re left to choose between a time-consuming search or laborious replication.

当您处理具有相似主题的一系列项目时,您可能会发现它们也共享位图以及矢量和声音对象。 如果您忘记了这些共享库位于哪个FLA中,则可以选择耗时的搜索还是繁琐的复制。

To avoid this situation, I create what I call master libraries for my buttons, movie clips, and animations, which I name according to their content. For example, I might create an FLA file that contains all plastic- or glossy-looking buttons, and call it Buttons - Plastic_Gloss.fla. I would then save this in a master directory. When I need them, I simply select File > Import > Import to Library…, locate my FLA file and, presto! The buttons appear in the Library Panel for use in the current project.

为避免这种情况,我为按钮,影片剪辑和动画创建了所谓的主库 ,并根据它们的内容命名。 例如,我可以创建一个包含所有具有Buttons - Plastic_Gloss.fla或光泽外观的按钮的FLA文件,并将其命名为Buttons - Plastic_Gloss.fla 。 然后,我将其保存在主目录中。 当我需要它们时,只需选择“文件”>“导入”>“导入到库...”,找到我的FLA文件,然后保存! 这些按钮出现在“库面板”中,供当前项目使用。

Even after several months, you may come back to a project to enhance it or add extra functionality. If you can’t remember where the source FLA files are, you’re going to waste a lot of time. Using this procedure allows you to be smart with your time and resources, and maintain a consistent look and feel across projects.

即使几个月后,您也可能会回到一个项目来增强它或添加其他功能。 如果您不记得源FLA文件在哪里,则将浪费大量时间。 通过使用此过程,您可以节省时间和资源,并在整个项目中保持一致的外观。

I think that, by now, we’ve covered most of the best practices and methods for increasing productivity when you work with Flash. The practices I’ve outlined here are only guidelines to make your life a little easier; they’re not hard and fast rules. So, feel free to embrace as many or as few of them as you wish.

我认为,到目前为止,我们已经涵盖了使用Flash时提高生产率的大多数最佳实践和方法。 我在这里概述的做法仅是使您的生活更轻松的准则; 他们不是一成不变的规则。 因此,可以随意包含任意数量的任意数量。

Now it’s time again to "holster up" and get ready for a showdown with some very cool ActionScripted effects!

现在是时候再次“整理”起来,并准备好使用一些非常酷的ActionScripted效果进行摊牌了!

随机运动 (Random Motion)

Have you ever wanted to create random movement for an object or a number of objects? There’s a simple technique that will take a single movie clip, create many copies of the object, and randomly place these on the canvas. It then creates the illusion of constant random movement. Best of all, this technique is easily extensible, allowing you, for example, to dynamically alter many of the properties of the object, including opacity and scale.

您是否曾经想为一个或多个对象创建随机运动? 有一种简单的技术,可以拍摄单个影片剪辑,创建对象的许多副本,然后将它们随机放置在画布上。 然后,它会产生不断随机运动的错觉。 最重要的是,此技术易于扩展,例如,允许您动态更改对象的许多属性,包括不透明度和缩放比例。

If you’d like to play the finished product before you proceed, have a look at Random_Motion.fla in the code archive.

如果您想在继续之前玩完成品,请查看代码档案中的Random_Motion.fla 。

设置场景 (Setting the Scene)

First, you’ll need to create a new Flash movie to showcase your effect.

首先,您需要创建一个新的Flash电影来展示您的效果。

Select File > New to create a new Flash movie.

选择“文件”>“新建”以创建新的Flash电影。 Select Modify > Document and set both the width and height of the movie to 300 pixels.

选择“修改”>“文档”,然后将影片的宽度和高度都设置为300像素。

In order to randomly place and move copies of your object, you’ll first need an object to use. In this example, we’ll create a movie clip container named MCWorld, which will contain another movie clip, called World.

为了随机放置和移动对象的副本,您首先需要使用一个对象。 在此示例中,我们将创建一个名为MCWorld的影片剪辑容器,其中将包含另一个名为World影片剪辑。

Select Insert > New Symbol, select Movie clip, and name the clip MCWorld. Click on the Advanced button to view the clip’s linkage parameters, select Export for ActionScript, and name the identifier MCWorld, as shown in Figure 3.1.

选择“插入”>“新符号”,选择“影片”剪辑,然后将剪辑命名为MCWorld 。 单击“高级”按钮以查看剪辑的链接参数,为“ ActionScript”选择“导出”,并命名标识符MCWorld ,如图3.1所示。

Figure 3.1. Set linkage properties for the parent movie clip.

图3.1。 设置父级影片剪辑的链接属性。

Note: We select the Export for ActionScript button because, in a moment, we’ll use ActionScript dynamically to create instances of this clip. To do that, we need to make it available to ActionScript by choosing this option and assigning the clip a unique identifier.

注意:我们选择“为ActionScript导出”按钮,因为稍后我们将动态使用ActionScript创建此剪辑的实例。 为此,我们需要通过选择此选项并为剪辑分配唯一的标识符,使其可用于ActionScript。

Create a graphic symbol that contains the object or image to which you want to assign random movement. Select Insert > New Symbol… and choose Graphic. Name this symbol World, then create the object either with the drawing tools, or by importing an image or other object from an external source.

创建一个图形符号,其中包含要为其分配随机运动的对象或图像。 选择“插入”>“新符号...”,然后选择“图形”。 将此符号命名为World ,然后使用绘图工具或通过从外部源导入图像或其他对象来创建对象。

The Library Panel should now contain a graphic symbol named World, as in Figure 3.2.

库面板现在应包含一个名为World的图形符号,如图3.2所示。

Figure 3.2. Add the child movie clip.

图3.2。 添加子影片剪辑。

Double click the MCWorld movie clip to open it. Drag an instance of the World symbol into it and name the instance World.

双击MCWorld影片剪辑以将其打开。 将World符号的一个实例拖到其中,并将其命名为World 。

添加动作脚本 (Adding the ActionScript)

Great! We’ve created a clip called MCWorld that contains a graphic called World. Now, we can begin to add the ActionScript that will control what takes place on the stage:

大! 我们创建了一个名为MCWorld的剪辑,其中包含一个名为World的图形。 现在,我们可以开始添加ActionScript来控制舞台上发生的事情:

Select Layer 1 within the main timeline, and give it the name ActionScript. Expand the Actions Panel (select Window > Development Panels > Actions or press F9).

在主时间轴中选择“第1层”,并将其命名为ActionScript。 展开“动作”面板(选择“窗口”>“开发面板”>“动作”或按F9 )。

Add the following code within the Actions Panel. This code creates thirty instances of the MCWorld clip and places them on the canvas at random. It also randomly alters the clips’ opacity.

在“动作面板”中添加以下代码。 这段代码创建了30个MCWorld剪辑实例,并将它们随机放置在画布上。 它还会随机更改剪辑的不透明度。

Example 3.4. Random_Motion.fla ActionScript : 1

示例3.4 Random_Motion.fla ActionScript:1

var numObjects = 30; for (i = 0; i < numObjects; i++)   {    var randomObject = attachMovie ('MCWorld', 'MCWorld' + i, i);    randomObject._x = random (300);    randomObject._y = random (300);    randomObject._alpha = random (100);   }

The key here is the attachMovie method, which lets you add a new movie clip to the current movie. The parameters we pass to this method are: the identifier we gave the clip in the library (MCWorld), a unique name for each clip instance (in this case, MCWorld with a number appended to it), and a number that indicates where to place the clip in the stacking order.

此处的关键是attachMovie方法,该方法可让您将新的影片剪辑添加到当前影片。 我们传递给此方法的参数是:我们在库中为剪辑提供的标识符( MCWorld ),每个剪辑实例的唯一名称(在这种情况下,为MCWorld附加一个数字),以及一个数字,该数字指示在何处将夹子按堆叠顺序放置。

Also of note in this code is the random function, which returns a random integer between zero (inclusive) and the specified number (exclusive). So random (300) returns a number from 0 to 299. We use this function to generate the position on the stage and the opacity for each instance we create.

该代码中还值得注意的是random函数,该函数返回一个介于零(包括)和指定数字(不包括)之间的随机整数。 因此, random (300)返回一个0到299之间的数字。我们使用此函数为创建的每个实例生成舞台上的位置和不透明度。

With our stage filled with randomly-positioned graphics, it’s now time to move them around.

我们的舞台上摆满了随机放置的图形,现在该移动它们了。

Double-click the MCWorld movie clip in the Library Panel to open it. Select Layer 1 and rename it ActionScript.

双击“库面板”中的MCWorld影片剪辑以将其打开。 选择第1层,并将其重命名为ActionScript。

Add the following code within the Actions Panel. It uses setInterval (a standard JavaScript function) to move the graphic symbol instance (World) to a new random position within two pixels of its current position every tenth of a second.

在“动作面板”中添加以下代码。 它使用setInterval (标准JavaScript函数)将图形符号实例(世界)每十分之一秒移动到其当前位置的两个像素内的新随机位置。

Example 3.5. Random_Motion.fla MCWorld : ActionScript : 1

示例3.5 Random_Motion.fla MCWorld :ActionScript:1

setInterval (Randomizer, 100); function ()   {    var xShift = random (5) - 2;    var yShift = random (5) - 2;    World._x += xShift;    World._y += yShift;   }

We could instead have used an onEnterFrame event handler to do this, but setInterval allows us to define the speed of the motion independent of the movie’s frame rate, which can be useful in many circumstances.

相反,我们可以使用onEnterFrame事件处理程序来执行此操作,但是setInterval允许我们独立于电影的帧速率来定义运动速度,这在许多情况下都非常有用。

测试电影 (Testing the Movie)

You’ve created your movie clips; now, let’s take the movie for a test-drive.

您已经创建了影片剪辑; 现在,让我们将影片试驾。

Select Control > Test Movie to preview your movie.

选择控制>测试影片以预览影片。

Figure 3.3. Preview the movie within Flash.

图3.3。 在Flash中预览电影。

If everything has gone according to plan, you should see an animated random movie similar to the one shown in Figure 3.3, where the x and y coordinates of the graphics change every tenth of a second.

如果一切都按计划进行,您应该看到类似于图3.3所示的动画随机电影,其中图形的x和y坐标每十分之一秒更改一次。

Random movement is simple to achieve using the basic building blocks outlined here. With experimentation, you’ll realize that the possible applications of this technique are limitless.

使用此处概述的基本构件很容易实现随机运动。 通过实验,您将意识到该技术的可能应用是无限的。

修改项 (Modifications)

It’s easy to modify the Randomizer function to alter the presentation of the movie. Changing various properties of the object at different points within the code can have quite dramatic effects – as we’re about to see.

修改Randomizer功能以更改电影的呈现很容易。 正如我们将要看到的,在代码中的不同点更改对象的各种属性可能会产生巨大的影响。

Flickering Opacity

忽明忽暗

Returning to the Randomizer function, let’s add an extra line that alters the opacity of the graphic.

返回Randomizer函数,让我们添加一条额外的线来更改图形的不透明度。

Locate the Randomizer function in the first frame of the MCWorld movie clip, and adjust it as follows:

在MCWorld影片剪辑的第一帧中找到“ Randomizer功能,并进行如下调整:

Example 3.6. Random_Motion_Alpha.fla MCWorld : ActionScript : 1 (excerpt)

示例3.6 Random_Motion_Alpha.fla MCWorld :ActionScript:1(节选)

function () {    var xShift = random (5) - 2;    var yShift = random (5) - 2;    World._x += xShift;    World._y += yShift;    World._alpha = random(100);   } Save and preview the movie.

保存和预览电影。

Every tenth of a second, at the same time each graphic is given a little nudge, the opacity is now reset to a random value between zero and 99%, producing a flickering effect. How easy was that?

每隔十分之一秒,同时向每个图形进行一点微调,现在将不透明度重置为零到99%之间的随机值,从而产生闪烁效果。 那有多容易?

You can even insert additional object properties to, for example, alter the horizontal and vertical scale of the object. Adding the following lines to the above code will randomly scale the graphic objects:

您甚至可以插入其他对象属性,例如,更改对象的水平和垂直比例。 在上面的代码中添加以下行将随机缩放图形对象:

World._xscale = random(100);    World._yscale = random(100);

World._xscale = random(100); World._yscale = random(100);

Increasing the Redraw Rate

增加提现率

As I mentioned earlier, using setInterval to trigger the changes to our graphics disconnected this animation from the frame rate of the movie. To increase the rate of the animation, simply change the delay specified when calling setInterval:

如前所述,使用setInterval触发对图形的更改会使该动画与电影的帧速率断开连接。 要提高动画的速率,只需更改调用setInterval时指定的延迟:

Example 3.7. Random_Motion.fla MCWorld : ActionScript : 1 (excerpt)

示例3.7 Random_Motion.fla MCWorld :ActionScript:1(节选)

setInterval(Randomizer, 100);

Reducing this value will increase the redraw rate (how often the Randomizer function is called). Bear in mind that these values are counted in milliseconds. To change the redraw rate to one second, you’d set the value to 1000. Keep in mind that decreasing the amount of time between redraws will increase the load on the CPU. If your movie uses a large number of objects, or objects that are complex, the user’s computer might have a tough time keeping up with the changes.

减小此值将增加重绘速率(多Randomizer调用一次Randomizer函数)。 请记住,这些值以毫秒为单位。 要将重绘速率更改为一秒,请将值设置为1000 。 请记住,减少两次重绘之间的时间会增加CPU的负载。 如果电影使用大量对象或复杂对象,则用户的计算机可能很难适应这些变化。

Increasing the Number of Objects

增加对象数量

To increase the number of objects initially drawn on the screen, simply change the numObjects variable in the main timeline code:

要增加最初在屏幕上绘制的对象数量,只需在主时间轴代码中更改numObjects变量:

Example 3.8. Random_Motion.fla ActionScript : 1 (excerpt)

示例3.8 Random_Motion.fla ActionScript:1(节选)

var numObjects = 30; for (i = 0; i < numObjects; i++)   {

The for loop uses this variable to control the number of objects created, so changing the number of objects couldn’t be easier!

for循环使用此变量来控制创建的对象数,因此更改对象数再简单不过了!

If those objects are complex, the CPU load will also increase proportionally. Be careful!

如果这些对象很复杂,CPU负载也会成比例增加。 小心!

Altering the Random Shift Value

改变随机移位值

After the objects are originally placed on the canvas at random, the Randomizer function shifts the x and y coordinates of the graphics every tenth of a second to give an appearance of jittery nervousness. To increase or decrease this quality, simply locate and edit the following lines within the Randomizer function:

将对象最初随机放置在画布上之后, Randomizer函数每隔十分之一秒移动图形的x和y坐标,以显示出紧张的神经质。 要提高或降低这种质量,只需在Randomizer函数中找到并编辑以下几行:

Example 3.9. Random_Motion.fla MCWorld : ActionScript : 1 (excerpt)

示例3.9 Random_Motion.fla MCWorld :ActionScript:1(节选)

var xShift = random(5) - 2;    var yShift = random(5) - 2;

var xShift = random(5) - 2; var yShift = random(5) - 2;

To keep your graphics from wandering off the stage, make sure that the first number on each line is twice the second number plus one. This relationship ensures that the calculated shift values tend to average out to zero. Of course, the easiest way to maintain this relationship is to make it explicit in the code:

为了防止图形在舞台上徘徊,请确保每行的第一个数字是第二个数字的两倍加一个。 这种关系确保了计算出的偏移值趋于平均为零。 当然,维护此关系的最简单方法是在代码中使其明确:

var nervousness = 2;    var xShift = random(nervousness * 2 + 1) - nervousness;    var yShift = random(nervousness * 2 + 1) - nervousness;

var nervousness = 2; var xShift = random(nervousness * 2 + 1) - nervousness; var yShift = random(nervousness * 2 + 1) - nervousness;

As you can see, once you become comfortable with editing the properties of objects, and randomizing their values, you can create some very interesting effects. The key to finding out what you can do is to experiment with values, explore the ActionScript reference, and have fun!

如您所见,一旦您熟悉了编辑对象的属性并随机化它们的值,就可以创建一些非常有趣的效果。 找出可以做什么的关键是尝试值,探索ActionScript参考并从中获得乐趣!

简单脚本掩蔽 (Simple Scripted Masking)

In this example, we’ll animate a mask from one point to another, based on input parameters we provide. I created this example to illustrate the traffic received by two Web servers hosting a number of Websites. The movie accepts two input parameters, then animates the mask accordingly. For this simple example, we’ll populate the variables statically by declaring them in the root of the timeline. A more realistic scenario would see the movie embedded in a database-driven Web page and the variables passed to the movie dynamically. We’ll cover importing external data in Chapter 8, External Data.

在此示例中,我们将基于提供的输入参数,将蒙版从一个点动画化为另一点。 我创建了此示例,以说明承载大量网站的两个Web服务器收到的流量。 电影接受两个输入参数,然后相应地对蒙版进行动画处理。 对于这个简单的示例,我们将通过在时间轴的根中声明变量来静态填充变量。 更为现实的情况是,将影片嵌入数据库驱动的网页中,并将变量动态传递给该影片。 我们将在第8章“外部数据”中介绍如何导入外部数据。

Figure 3.4. This simple scripted masking effect animates a mask between two points.

图3.4。 这种简单的脚本化遮罩效果可在两点之间设置遮罩动画。

The finished product is shown in Figure 3.4. Let’s look at how this effect is accomplished. To skip straight to modifying the effect , locate the file called Simple_Animation_Masking.fla in the code archive.

成品如图3.4所示。 让我们看看如何实现这种效果。 要直接跳过修改效果, Simple_Animation_Masking.fla在代码档案中找到名为Simple_Animation_Masking.fla的文件。

Create a new movie that’s 200 pixels wide and 40 pixels high. Alter the frame rate to 24 fps for a nice, smooth animation.

创建200像素宽和40像素高的新电影。 将帧速率更改为24 fps,以获得漂亮,流畅的动画。 Create the folders and layers shown in Figure 3.5 below.

创建下面的图3.5中所示的文件夹和层。

Figure 3.5. Organize the layers and folders for the scripted masking effect.

图3.5。 组织图层和文件夹以实现脚本化的遮罩效果。

We now need to create the background bar that we’ll mask. In this example, I created a bar that’s white on the left and gradually became red toward the right, indicating the increase in server load as traffic levels grow.

现在,我们需要创建要掩盖的背景栏。 在此示例中,我创建了一个左侧为白色的栏,并逐渐向右侧变为红色,这表明服务器流量随着流量水平的增加而增加。

Add two static text fields within the textlabels layer and enter text that reads, Server 1 and Server 2, to let users know what each bar represents. We don’t need to convert these to movie clips, as we won’t reference them in our ActionScript. Move them to (1, 0) and (1, 25) respectively.

在textlabels图层中添加两个静态文本字段,然后输入读取内容为Server 1和Server 2文本,以使用户知道每个栏代表什么。 我们不需要将它们转换为影片剪辑,因为我们不会在ActionScript中引用它们。 将它们分别移到(1,0)和(1,25)。

Within the Server1Background layer, create a new rectangle that’s 100 pixels wide and 9 pixels high. Select a gradient fill that changes from white on the left, through yellow and orange, to red on the right of the rectangle. Select the rectangle, then select Insert > Convert to Symbol…. Choose to create a Graphic named Background.

在Server1Background层中,创建一个新的矩形,该矩形的宽度为100像素,高度为9像素。 选择一个渐变填充,该填充将从矩形的左侧的白色变为黄色和橙色,然后变为矩形的右侧的红色。 选择矩形,然后选择“插入”>“转换为符号…”。 选择创建一个名为Background的图形。

Name the existing instance of Background backg1 and move it to (50, 3). Drag a second instance of the graphic from the Library Panel into the Server2Background layer naming it backg2, and move it to (50, 29). Lock these two layers; we don’t need to modify them any further.

命名Background backg1的现有实例,并将其移至( Background backg1 )。 将图形的第二个实例从“库”面板拖到命名为backg2的Server2Background层中,然后将其移动到( backg2 )。 锁定这两层; 我们不需要对其进行任何进一步的修改。

Now that we’ve created the backgrounds, we can build the masks we’ll control via ActionScript:

现在,我们已经创建了背景,我们可以构建将通过ActionScript控制的蒙版:

Create a new rectangle, with no stroke and a solid white fill, that’s 5 pixels wide and 9 pixels high (this exactly matches the height of the movie clip we will mask). Convert the rectangle to a graphic symbol named ServerAnimation, and place instances of the graphic in the Server1Mask and Server2Mask layers.

创建一个新的矩形,该矩形没有笔触,并且具有白色实心填充,其宽度为5像素,高度为9像素(这与我们将遮盖的影片剪辑的高度完全匹配)。 将矩形转换为名为ServerAnimation的图形符号,并将图形的实例放置在Server1Mask和Server2Mask图层中。

Name the instances server1Mask and server2Mask respectively. (This is important as we will reference these clips in ActionScript later.) Move them to (50, 3) and (50, 29), so they’re flush with the left edge of the backg1 and backg2 movie clips.

分别命名实例server1Mask和server2Mask 。 (这很重要,因为稍后我们将在ActionScript中引用这些剪辑。)将它们移动到(50,3)和(50,29),以便它们与backg1和backg2影片剪辑的左边缘齐平。

To achieve the desired effect, we need to set up the server1Mask and server2Mask graphics so that they work as masks for the background graphics beneath them. Locate the Server1Mask and Server2Mask layers, right-click on each, and select Mask (see Figure 3.6).

为了获得理想的效果,我们需要设置server1Mask和server2Mask图形,以便它们充当其下方背景图形的遮罩 。 找到Server1Mask和Server2Mask层,在每个层上单击鼠标右键,然后选择Mask(见图3.6)。

Figure 3.6. Convert the dynamic movie clips into masks.

图3.6。 将动态影片剪辑转换为蒙版。

When the movie runs, only those portions of the Background graphics in Server1Background and Server2Background that are covered by the ServerAnimation graphics in Server1Mask and Server2Mask will be visible.

电影运行时,只有Server1Background和Server2Background中Background图形中由Server1Mask和Server2Mask中ServerAnimation图形所覆盖的那些部分才可见。

We now need to animate the two mask graphics so that they reveal the appropriate portions of the Background graphics. Select the Actions layer, and, with the Actions Panel open, add the following code to the first frame:

现在,我们需要对两个蒙版图形进行动画处理,以使它们显示Background图形的适当部分。 选择“动作”层,然后在“动作面板”打开的情况下,将以下代码添加到第一帧:

Example 3.10. Simple_Animation_Masking.fla Actions : 1 (Excerpt)

示例3.10 Simple_Animation_Masking.fla动作:1(摘录)

var server1load = 25; var server2load = 75;   function animate (server, serverload)   {    server.onEnterFrame = function ()    {      if (this._width <= serverload)        this._width += 2;    };   }   animate (server1Mask, server1load);   animate (server2Mask, server2load);

That’s all the code we need to alter the rectangles to make the two bar graphs grow to their assigned lengths. Let’s look at how it’s done.

这就是我们需要更改矩形以使两个条形图增长到其指定长度的所有代码。 让我们看看它是如何完成的。

First, we create two variables with values that represent (as a percentage) how much of the Background graphic we want to display for each server. The math is kept simple because the backg1 and backg2 graphics are exactly 100 pixels wide.

首先,我们创建两个变量,其值表示(以百分比表示)我们要为每个服务器显示多少Background图形。 数学保持简单,因为backg1和backg2图形的宽度恰好为100像素。

The animate function takes a reference to one of our mask graphics and sets up an onEnterFrame event handler to increase its width by two pixels per frame up to a specified value. The code finishes by calling animate for each of the two mask graphics, passing each of the two server load values.

animate函数引用我们的一个蒙版图形,并设置一个onEnterFrame事件处理程序,以将其宽度每帧增加两个像素,直到指定值。 该代码通过为两个蒙版图形中的每一个调用animate并传递两个服务器负载值中的每一个来完成。

Save your movie and preview it. Notice how the two masks grow to sizes dictated by the server1load and server2load variables. It’s a pretty cool effect that you can easily include in your projects, creating bar graphs or other visual displays of increases occurring over time.

保存电影并预览。 请注意,两个掩码如何增长到由server1load和server2load变量指定的大小。 您可以轻松地将其包含在项目中,创建条形图或其他随时间推移而增加的可视显示,这是一个非常酷的效果。

添加文字标签 (Adding Text Labels)

So far, we’ve managed to animate masks over time to create a slick, animated bar graph. This is great, but we don’t know what values the bars represent. Let’s add a text label to each graph to complete the effect:

到目前为止,我们已经成功地对蒙版进行了动画处理,以创建一个光滑的动画条形图。 很好,但是我们不知道这些条代表什么值。 让我们为每个图形添加一个文本标签以完成效果:

Create a new graphic symbol named serverinfo containing a dynamic text field that’s 34 pixels wide and 15 pixels high. In the Property Inspector for the text field, set the Var name to serverload (which we’ll use to set the value to be displayed for each server). Also in the Property Inspector, click Character… and make sure that Embed font outlines for is set to Basic Latin (or All Characters in Flash MX).

创建一个名为serverinfo的新图形符号,其中包含一个动态文本字段,该文本字段的宽度为34像素,高度为15像素。 在文本字段的属性检查器中,将Var名称设置为serverload (我们将使用它来设置要为每个服务器显示的值)。 另外,在属性检查器中,单击“字符...”,并确保将“嵌入字体轮廓”设置为“基本拉丁语”(或Flash MX中的“所有字符”)。

Drag two instances of this new symbol into the first frame of the Labels layer of the Animated Labels folder. Name the instances server1info and server2info. Position them at (54, 1) and (54, 27) respectively.

将这个新符号的两个实例拖到Animated Labels文件夹的Labels层的第一帧中。 将实例命名为server1info和server2info 。 将它们分别放在(54,1)和(54,27)。

Navigate back to the first frame of the Actions layer in the root of the movie. Insert the following code below the first two variables:

导航回到影片根目录中“动作”图层的第一帧。 在前两个变量下面插入以下代码:

Example 3.11. Simple_Animation_Masking.fla Actions : 1 (excerpt)

示例3.11 Simple_Animation_Masking.fla动作:1(节选)

server1info.serverload = server1load + "%"; server2info.serverload = server2load + "%";

This code sets the serverload variable inside each of the two serverinfo symbols, controlling the text they display.

此代码在两个serverinfo符号中的每个符号内设置serverload变量,以控制它们显示的文本。

Save and preview your work.

保存并预览您的工作。

You’ll notice that the values for each of the bars now simply sit where we placed them. They look a little out of place, given the movement that is occurring. We’d better animate them so that they fit in.

您会注意到,每个条形的值现在都位于我们放置它们的位置。 考虑到正在发生的运动,它们看上去有些不合时宜。 我们最好为它们设置动画,以使其适合。

Still in the first frame of the Actions layer, add the following function declaration:

仍在Actions层的第一帧中,添加以下函数声明:

Example 3.12. Simple_Animation_Masking.fla Actions : 1 (excerpt)

示例3.12 Simple_Animation_Masking.fla动作:1(节选)

function moveText (serverinfo, serverload) {    var startPos = serverinfo._x;    serverinfo.onEnterFrame = function ()    {      if (this._x <= startPos + serverload)        this._x += 2;    };   }

This function works just like the animate function, but it moves the graphic we pass to it horizontally instead of setting its width.

此功能的工作方式与animate功能一样,但是它会将我们传递给它的图形水平移动,而不是设置其宽度。

Try some speedy text For a slightly different effect that adds to the movie’s visual appeal, you could have the text move more quickly than the bars by increasing the step size of the movement from two to four.

尝试一些快速的文本要使电影的视觉效果略有不同,可以通过将步长从2增大到4,使文本的移动速度比条形移动的速度更快。

All that’s left is to call this function for each of our text labels to kick off their animation.

剩下的就是为我们的每个文本标签调用此函数以启动其动画。

Add the following code:

添加以下代码:

Example 3.13. Simple_Animation_Masking.fla Actions : 1 (excerpt)

示例3.13 Simple_Animation_Masking.fla动作:1(节选)

moveText (server1info, server1load); moveText (server2info, server2load); Save your movie and preview it.

保存电影并预览。

That’s it! This scripted animation of the text fields completes the effect and looks very cool!

而已! 这个文本字段的脚本动画可以完成效果,而且看起来很酷!

修改项 (Modifications)

You can easily modify this effect to include more items. Simply create more bars, and reference them when the movie loads, to produce interesting graphs. This effect could also generate moving bars that slide into place as the movie is loaded. The direction in which you choose to take this effect really is up to you.

您可以轻松修改此效果以包括更多项目。 只需创建更多的条形,并在影片加载时引用它们,即可生成有趣的图形。 此效果还可能生成移动的条,这些条会在加载影片时滑入到位。 The direction in which you choose to take this effect really is up to you.

Raindrops Keep Falling on My Head (Raindrops Keep Falling on My Head)

One of the quickest ways to create an animated effect is to take an animation and duplicate it multiple times on the stage. The success of this technique depends on the original animation being cool enough to warrant this kind of replication. In this example, we’ll create a quick rainfall effect by duplicating a movie clip several times on the canvas. Sound simple? Let’s look at how it’s done.

One of the quickest ways to create an animated effect is to take an animation and duplicate it multiple times on the stage. The success of this technique depends on the original animation being cool enough to warrant this kind of replication. In this example, we'll create a quick rainfall effect by duplicating a movie clip several times on the canvas. Sound simple? Let's look at how it's done.

To skip the details and jump straight into the effect, locate the Duplication.fla file in the code archive.

To skip the details and jump straight into the effect, locate the Duplication.fla file in the code archive.

Figure 3.7. This simple raindrop effect is created using duplication.

Figure 3.7. This simple raindrop effect is created using duplication.

设置场景 (Setting the Scene)

First, we need to create the movie clip we’ll reference in our control code.

First, we need to create the movie clip we'll reference in our control code.

Create a new movie that’s 350 pixels wide and 400 pixels high. Increase the frame rate to 18 fps. Create three layers and name them Actions, Raindrops and Background.

Create a new movie that's 350 pixels wide and 400 pixels high. Increase the frame rate to 18 fps. Create three layers and name them Actions, Raindrops and Background. Create a graphic symbol named Raindrop and use the drawing tools to draw a falling drop of water.

Create a graphic symbol named Raindrop and use the drawing tools to draw a falling drop of water.

Create a new movie clip symbol, also named Raindrop. Make sure it’s open for editing, then drag an instance of the Raindrop graphic from the Library Panel onto the stage. Name the instance Raindrop. Position it at (0, 0) within the clip.

Create a new movie clip symbol, also named Raindrop . Make sure it's open for editing, then drag an instance of the Raindrop graphic from the Library Panel onto the stage. Name the instance Raindrop . Position it at (0, 0) within the clip.

Create a new keyframe within the movie clip at frame 40. Select frame 1, right-click, and select Motion Tween. Shift back to frame 40 and move the raindrop graphic to the bottom of the stage – about (0, 390).

Create a new keyframe within the movie clip at frame 40. Select frame 1, right-click, and select Motion Tween. Shift back to frame 40 and move the raindrop graphic to the bottom of the stage – about (0, 390).

In the Library Panel, duplicate the Raindrop movie clip you created, and name this duplicate RaindropSlow. Edit the RaindropSlow movie clip, grab the end keyframe in the timeline, and drag it out to frame 80. This will produce a slower animation.

In the Library Panel, duplicate the Raindrop movie clip you created, and name this duplicate RaindropSlow . Edit the RaindropSlow movie clip, grab the end keyframe in the timeline, and drag it out to frame 80. This will produce a slower animation.

We will use these two Raindrop clips to create a subtle effect a little later. Now let’s assemble the main scene:

We will use these two Raindrop clips to create a subtle effect a little later. Now let's assemble the main scene:

Drag one instance each of the Raindrop and RaindropSlow movie clips into the Raindrops layer. Name them raindrop and raindropSlow, respectively.

Drag one instance each of the Raindrop and RaindropSlow movie clips into the Raindrops layer. Name them raindrop and raindropSlow , respectively.

Move the two clips so they sit near the top of the stage, but outside its left edge. I placed them at (-45, 10) and (-30, 10). If you can’t see past the edge of the stage, you may have to choose View > Work Area first. The goal here is to have the drops as part of the scene, but not visible on stage.

Move the two clips so they sit near the top of the stage, but outside its left edge. I placed them at (-45, 10) and (-30, 10). If you can't see past the edge of the stage, you may have to choose View > Work Area first. The goal here is to have the drops as part of the scene, but not visible on stage. Select the Background layer and add some rolling hills and a storm cloud to it using the drawing tools. To finish, lock this layer.

Select the Background layer and add some rolling hills and a storm cloud to it using the drawing tools. To finish, lock this layer.
Adding the Control Code (Adding the Control Code)

All the graphics are created and in place on the stage; we just need to duplicate them a few times. If you were to preview the movie now, you’d see two single raindrops, one falling faster than the other, off the side of the stage. I think we’d better spice things up with a little ActionScript.

All the graphics are created and in place on the stage; we just need to duplicate them a few times. If you were to preview the movie now, you'd see two single raindrops, one falling faster than the other, off the side of the stage. I think we'd better spice things up with a little ActionScript.

Navigate to the first frame of the Actions layer within the timeline and add the following code:

Navigate to the first frame of the Actions layer within the timeline and add the following code:

Example 3.14. Duplication.fla Actions : 1

Example 3.14. Duplication.fla Actions : 1

for (i = 0; i < 50; i++) {      var newDrop = raindrop.duplicateMovieClip ("raindrop" + i,          i);      newDrop._x = random (350);      newDrop._y = random (20);     }

Here, we use the duplicateMovieClip method to create 50 copies of the raindrop clip that resides on the root of the timeline. If you want more raindrops, you can change the number 50 in the for loop to whatever you like. However, beware of the increased CPU load that comes with large numbers of movie clips.

Here, we use the duplicateMovieClip method to create 50 copies of the raindrop clip that resides on the root of the timeline. If you want more raindrops, you can change the number 50 in the for loop to whatever you like. However, beware of the increased CPU load that comes with large numbers of movie clips.

As with the attachMovie method we saw earlier in this chapter, duplicateMovieClip requires parameters that set the instance name for the new movie clip (in this case, raindrop with a number appended to it) and its position in the stacking order.

As with the attachMovie method we saw earlier in this chapter, duplicateMovieClip requires parameters that set the instance name for the new movie clip (in this case, raindrop with a number appended to it) and its position in the stacking order.

After we duplicate the movie clip, we assign each duplicate a random horizontal location between zero and the right-hand side of the stage (x=350). We also shift each instance of the clip vertically using a random value between zero and twenty, to make it look as if the raindrops are falling out of different parts of the cloud.

After we duplicate the movie clip, we assign each duplicate a random horizontal location between zero and the right-hand side of the stage (x=350). We also shift each instance of the clip vertically using a random value between zero and twenty, to make it look as if the raindrops are falling out of different parts of the cloud.

Save your movie and preview it within Flash. You’ll notice that, even though the raindrops appear to be randomly spaced along the x and y axes, they fall in a straight line. It certainly doesn’t rain like this in my neighborhood! We can quickly remedy the situation by introducing more random elements to the code.

Save your movie and preview it within Flash. You'll notice that, even though the raindrops appear to be randomly spaced along the x and y axes, they fall in a straight line. It certainly doesn't rain like this in my neighborhood! We can quickly remedy the situation by introducing more random elements to the code. Replace the code in the Actions Panel with the following:

Replace the code in the Actions Panel with the following:

Example 3.15. Duplication.fla Actions : 1 (excerpt)

Example 3.15. Duplication.fla Actions : 1 (excerpt)

for (i = 0; i < 50; i++) {      var newDrop = raindrop.duplicateMovieClip ("raindrop" + i,          i);      newDrop._x = random (350);      newDrop._y = random (20);      newDrop.gotoAndPlay(random(40) + 1);     }

Notice the extra line of code within this block, shown in bold. This little snippet may look insignificant, but it brings the animation to life. Using the gotoAndPlay method of each new clip, the animation is advanced to a random frame between 1 and 40 (remember, random(40) generates values from 0 to 39) and then played from that point.

Notice the extra line of code within this block, shown in bold. This little snippet may look insignificant, but it brings the animation to life. Using the gotoAndPlay method of each new clip, the animation is advanced to a random frame between 1 and 40 (remember, random(40) generates values from 0 to 39) and then played from that point.

Save and preview your movie. You’ll notice that the raindrops now fall much more naturally than they did before.

Save and preview your movie. You'll notice that the raindrops now fall much more naturally than they did before.

Although this animation is simple to accomplish, it’s effective in its execution. There are numerous ways to extend this example and make it more interesting. Let’s take a little time to examine them now.

Although this animation is simple to accomplish, it's effective in its execution. There are numerous ways to extend this example and make it more interesting. Let's take a little time to examine them now.

Add Some Randomness (Add Some Randomness)

To make this effect more engaging, we can modify the horizontal scale and alpha values of each drop of rain as it’s created:

To make this effect more engaging, we can modify the horizontal scale and alpha values of each drop of rain as it's created:

Modify the code in the Actions layer as follows:

Modify the code in the Actions layer as follows:

Example 3.16. Duplication.fla Actions : 1 (excerpt)

Example 3.16. Duplication.fla Actions : 1 (excerpt)

for (i = 0; i < 50; i++) {      var newDrop = raindrop.duplicateMovieClip ("raindrop" + i,          i);      newDrop._x = random (350);      newDrop._y = random (20);      newDrop._xscale = random (100);      newDrop._alpha = random (50);      newDrop.gotoAndPlay (random (40) + 1);     }

Save and preview the movie. You’ll see raindrops with differing widths – from little, skinny drops to big, fat ones. Each drop’s opacity value is also picked at random between zero and 50%.

Save and preview the movie. You'll see raindrops with differing widths – from little, skinny drops to big, fat ones. Each drop's opacity value is also picked at random between zero and 50%.

And the Heavens Opened… (And the Heavens Opened…)

Remember the movie clip we created earlier that was slower than the original raindrop? We have a use for it now! Not all raindrops fall at the same speed, and we can use that clip to make our animation more realistic. Let’s add some code that will include the second raindrop movie clip in our animation.

Remember the movie clip we created earlier that was slower than the original raindrop? We have a use for it now! Not all raindrops fall at the same speed, and we can use that clip to make our animation more realistic. Let's add some code that will include the second raindrop movie clip in our animation.

To edit this effect for your own needs, locate Duplication_Modification.fla in the code archive.

To edit this effect for your own needs, locate Duplication_Modification.fla in the code archive.

Add the following code below the existing code in the first frame of the Actions layer:

Add the following code below the existing code in the first frame of the Actions layer:

Example 3.17. Duplication_Modification.fla Actions : 1 (excerpt)

Example 3.17. Duplication_Modification.fla Actions : 1 (excerpt)

for (j = i; j < i + 100; j++) {      var newDrop = raindropSlow.duplicateMovieClip (          "raindropSlow" + j, j);      newDrop._x = random (350);      newDrop._y = random (20);      newDrop._xscale = random (100);      newDrop._alpha = random (25);      newDrop.gotoAndPlay (random (80) + 1);     }

This works just like the previous block of code: the for loop creates a number of duplicates of the movie clip, then uses the random function to set values for various properties of the duplicates. Here are the differences in this second block of code:

This works just like the previous block of code: the for loop creates a number of duplicates of the movie clip, then uses the random function to set values for various properties of the duplicates. Here are the differences in this second block of code:

Our for loop counts to 100, instead of 50, so we’ll create twice as many duplicates.

Our for loop counts to 100, instead of 50, so we'll create twice as many duplicates.

We create duplicates of the raindropSlow clip this time.

We create duplicates of the raindropSlow clip this time.

We use a new counter variable for this loop (j), and add it to the count at the end of our previous loop (i) when setting the stacking order of the new duplicates. This ensures that all the drops get their own place in the stacking order. (Otherwise, the slow raindrops would replace the fast raindrops on the stage!)

We use a new counter variable for this loop ( j ), and add it to the count at the end of our previous loop ( i ) when setting the stacking order of the new duplicates. This ensures that all the drops get their own place in the stacking order. (Otherwise, the slow raindrops would replace the fast raindrops on the stage!)

We set alpha values between zero and 25% for our slow raindrops, to make them appear further away.

We set alpha values between zero and 25% for our slow raindrops, to make them appear further away.

Because RaindropSlow is 80 frames in length instead of forty, we have adjusted the value we pass to random on the last line.

Because RaindropSlow is 80 frames in length instead of forty, we have adjusted the value we pass to random on the last line.

That’s it for the raindrops! Now let’s see if we can further enhance the scene with some more complicated effects.

That's it for the raindrops! Now let's see if we can further enhance the scene with some more complicated effects.

Creating a Parallax Cloud Structure (Creating a Parallax Cloud Structure)

Like raindrops, the movement of clouds is extremely random – each cloud moves at a different speed. With some clever math and a few simple cloud movie clips, you can create an interesting effect that adds depth to the scene (see Figure 3.8).

Like raindrops, the movement of clouds is extremely random – each cloud moves at a different speed. With some clever math and a few simple cloud movie clips, you can create an interesting effect that adds depth to the scene (see Figure 3.8).

Figure 3.8. By choosing the right random values, you can create this smooth cloud movement.

Figure 3.8. By choosing the right random values, you can create this smooth cloud movement.

We’ll start where we left the example in the previous section. To jump straight to the finished product, locate in the code archive.

We'll start where we left the example in the previous section. To jump straight to the finished product, locate in the code archive.

Create two new movie clip symbols, named LargeCloud and SmallCloud, and place an image that resembles a cloud in each. Make the cloud in the SmallCloud clip about half the size of its counterpart in LargeCloud.

Create two new movie clip symbols, named LargeCloud and SmallCloud , and place an image that resembles a cloud in each. Make the cloud in the SmallCloud clip about half the size of its counterpart in LargeCloud .

Create above the RainDrops layer a new layer called Clouds, and drag instances of the two new movie clips into this layer. Name them according to their master movie clips (largeCloud and smallCloud, respectively). Again, place them off the side of the stage.

Create above the RainDrops layer a new layer called Clouds, and drag instances of the two new movie clips into this layer. Name them according to their master movie clips ( largeCloud and smallCloud , respectively). Again, place them off the side of the stage.

We’ll use these two clouds in a manner similar to our work with the two raindrops, duplicating them with ActionScript code to create a random scene. To add a feeling of depth to our cloud structure, we’ll create a parallax effect. This involves making faraway objects (our small clouds) move more slowly than nearby objects (our large clouds), which creates a sense of perspective and depth.

We'll use these two clouds in a manner similar to our work with the two raindrops, duplicating them with ActionScript code to create a random scene. To add a feeling of depth to our cloud structure, we'll create a parallax effect. This involves making faraway objects (our small clouds) move more slowly than nearby objects (our large clouds), which creates a sense of perspective and depth.

Add the following code to frame 1 of the Actions layer, beneath the existing code:

Add the following code to frame 1 of the Actions layer, beneath the existing code:

Example 3.18. Duplication_Modification_Clouds.fla Actions : 1 (excerpt)

Example 3.18. Duplication_Modification_Clouds.fla Actions : 1 (excerpt)

for (i = j; i < j + 60; i++) {      var newCloud = smallCloud.duplicateMovieClip (          "smallCloud" + i, i);      newCloud._alpha = random (100);      newCloud._x = random (450) - 100;      newCloud._y = random (60) + 10;      newCloud.step = random(4);      newCloud.onEnterFrame = cloudStep;     }     for (j = i; j < i + 30; j++)     {      var newCloud = largeCloud.duplicateMovieClip (          "largeCloud" + j, j);      newCloud._alpha = random (100);      newCloud._x = random (450) - 100;      newCloud._y = random (40) - 20;      newCloud.step = random(4) + 2;      newCloud.onEnterFrame = cloudStep;     }     function cloudStep()     {      if (this._x >= 350) this._x = -100;      this._x += this.step;     }

As you can probably figure out by examining the code, we’re creating 60 duplicates of the small cloud and thirty duplicates of the large cloud. Our loops continue to use the i and j variables so that the clouds are added to the top of the stacking order and the raindrops appear to come from behind or within them.

As you can probably figure out by examining the code, we're creating 60 duplicates of the small cloud and thirty duplicates of the large cloud. Our loops continue to use the i and j variables so that the clouds are added to the top of the stacking order and the raindrops appear to come from behind or within them.

For each cloud we assign a random opacity between 0% and 99%, and a random horizontal position between -100 and 350. Remember that this is the position of the left edge of the cloud, so we need those negative values to allow for clouds partially obscured by the left edge of the stage.

For each cloud we assign a random opacity between 0% and 99%, and a random horizontal position between -100 and 350. Remember that this is the position of the left edge of the cloud, so we need those negative values to allow for clouds partially obscured by the left edge of the stage.

To develop the sense of depth even further, and to ensure our small clouds aren’t obscured by the large clouds, we make our small clouds sit lower on the stage (with random vertical positions from 10 to 69) than our large clouds (from -20 to 19). With the small clouds closer to the horizon, they will seem further away.

To develop the sense of depth even further, and to ensure our small clouds aren't obscured by the large clouds, we make our small clouds sit lower on the stage (with random vertical positions from 10 to 69) than our large clouds (from -20 to 19). With the small clouds closer to the horizon, they will seem further away.

Now for the crux of our parallax effect: the motion of the clouds. All of our clouds will move across the stage from left to right. Each cloud will have its own randomly assigned step size, which indicates the number of pixels per frame it should move. For the small clouds, we generate step sizes from zero to three pixels, while the large clouds will get step sizes from two to five pixels. We store each cloud’s step size into a variable called step within the cloud’s movie clip (newCloud.step).

Now for the crux of our parallax effect: the motion of the clouds. All of our clouds will move across the stage from left to right. Each cloud will have its own randomly assigned step size, which indicates the number of pixels per frame it should move. For the small clouds, we generate step sizes from zero to three pixels, while the large clouds will get step sizes from two to five pixels. We store each cloud's step size into a variable called step within the cloud's movie clip ( newCloud.step ).

Finally, we add an onEnterFrame event handler for each of the clouds, all of which will use a common function called cloudStep. This uses the clip’s step size to move it to the right until it reaches a horizontal position of 350 pixels, at which point it’s sent back to -100.

Finally, we add an onEnterFrame event handler for each of the clouds, all of which will use a common function called cloudStep . This uses the clip's step size to move it to the right until it reaches a horizontal position of 350 pixels, at which point it's sent back to -100.

Save the movie and preview it. To see how the effect looks without the objects running off the stage, export the movie to a SWF file and double-click it to view the movie in Flash Player.

Save the movie and preview it. To see how the effect looks without the objects running off the stage, export the movie to a SWF file and double-click it to view the movie in Flash Player.

That’s a pretty cool effect! All the clouds move at different speeds, so the effect doesn’t look "manufactured." But there is still more we can add to this scene…

That's a pretty cool effect! All the clouds move at different speeds, so the effect doesn't look "manufactured." But there is still more we can add to this scene…

Creating a Lightning Flash (Creating a Lightning Flash)

That storm we just created looks pretty good, but it could do with some sheet lightning to add that finishing touch.

That storm we just created looks pretty good, but it could do with some sheet lightning to add that finishing touch.

We’ll pick up where we left off in the previous section. To jump straight to the end of this example, locate Duplication_Modification_Clouds_And_Flash.fla from the code archive.

We'll pick up where we left off in the previous section. To jump straight to the end of this example, locate Duplication_Modification_Clouds_And_Flash.fla from the code archive.

Create a new movie clip named LightningFlash and add a rectangle that fills the stage (350×400 pixels). Give it a white gradient fill, fading from 100% opacity at the center of the rectangle to 0% opacity at the bottom edge of the rectangle.

Create a new movie clip named LightningFlash and add a rectangle that fills the stage (350×400 pixels). Give it a white gradient fill, fading from 100% opacity at the center of the rectangle to 0% opacity at the bottom edge of the rectangle.

Back in the main timeline, create a new layer named Flash above the Clouds layer and drag an instance of the new movie clip into it. Name the instance flash. You can lock and hide the layer – we won’t need to edit it again.

Back in the main timeline, create a new layer named Flash above the Clouds layer and drag an instance of the new movie clip into it. Name the instance flash . You can lock and hide the layer – we won't need to edit it again.

Now that we’ve created the movie clip, we can add the control code:

Now that we've created the movie clip, we can add the control code:

Once again, add the following code to the end of frame 1 of the Actions layer:

Once again, add the following code to the end of frame 1 of the Actions layer:

Example 3.19. Duplication_Modification_Clouds_And_Flash.fla Actions : 1 (excerpt)

Example 3.19. Duplication_Modification_Clouds_And_Flash.fla Actions : 1 (excerpt)

flash._alpha = 0; flash.onEnterFrame = function ()     {      var flashControl = random (10);      if (flashControl >= 9 ||          flash._alpha > 0 && flashControl >= 5)      {        flash._alpha += random (65);        if (flash._alpha > 65)        {          flash._alpha = 0;        }      }     };

We start by setting the flash movie clip’s opacity to zero, so that the lightning doesn’t appear until we want it to.

We start by setting the flash movie clip's opacity to zero, so that the lightning doesn't appear until we want it to.

Next, we tackle the onEnterFrame event handler, which will control the opacity of the lightning for each frame of the movie.

Next, we tackle the onEnterFrame event handler, which will control the opacity of the lightning for each frame of the movie.

Even in the worst storms, lightning is an intermittent thing. After some fiddling, I’ve decided I want a 10% chance that a flash of lightning will occur in any given frame. So I use random to generate a number (flashControl) between zero and nine and write my code so that it initiates a lightning flash whenever that number is nine.

Even in the worst storms, lightning is an intermittent thing. After some fiddling, I've decided I want a 10% chance that a flash of lightning will occur in any given frame. So I use random to generate a number ( flashControl ) between zero and nine and write my code so that it initiates a lightning flash whenever that number is nine.

Within the body of the if statement, the code goes on to add a random value between 0 and 64 to the opacity of the flash movie clip. Once this takes place, we want the lightning to continue to grow in brightness until it hits the maximum brightness for a flash of lightning (which, after some experimentation, I’ve decided is 65% opacity. At that point, we set the opacity back to zero and wait for the next flash of lightning.

Within the body of the if statement, the code goes on to add a random value between 0 and 64 to the opacity of the flash movie clip. Once this takes place, we want the lightning to continue to grow in brightness until it hits the maximum brightness for a flash of lightning (which, after some experimentation, I've decided is 65% opacity. At that point, we set the opacity back to zero and wait for the next flash of lightning.

When a lightning flash occurs, we don’t want to wait for that one-in-ten chance of lightning to make the existing flash brighter. And, at the same time, we can add some variety to our lightning flashes by not having them grow brighter with every frame. That’s why the condition in the if statement is so complex – if a lightning flash is in progress (which we detect by checking if flash._alpha is greater than zero), then we allow the flash to grow brighter 50% of the time (whenever flashControl is five or greater).

When a lightning flash occurs, we don't want to wait for that one-in-ten chance of lightning to make the existing flash brighter. And, at the same time, we can add some variety to our lightning flashes by not having them grow brighter with every frame. That's why the condition in the if statement is so complex – if a lightning flash is in progress (which we detect by checking if flash._alpha is greater than zero), then we allow the flash to grow brighter 50% of the time (whenever flashControl is five or greater).

Save the movie and preview it in Flash.

Save the movie and preview it in Flash.

The conditions we’ve employed here, including the use of random values, cause the _alpha value of the flash movie clip to flash in and out, producing quite a stormy scene. Feel free to experiment with the probabilities I’ve put in place to make the storm more or less severe.

The conditions we've employed here, including the use of random values, cause the _alpha value of the flash movie clip to flash in and out, producing quite a stormy scene. Feel free to experiment with the probabilities I've put in place to make the storm more or less severe.

Creating User-driven Motion (Creating User-driven Motion)

In this example, we’ll create motion based on user input. When the user clicks one button, objects slide into place; when another button is clicked, the objects slide back to their starting points (see Figure 3.9). This example builds upon previous animation examples and is fully scripted – there’s not a motion tween in sight!

In this example, we'll create motion based on user input. When the user clicks one button, objects slide into place; when another button is clicked, the objects slide back to their starting points (see Figure 3.9). This example builds upon previous animation examples and is fully scripted – there's not a motion tween in sight!

Figure 3.9. This effect is driven by user input.

Figure 3.9. This effect is driven by user input.

If you don’t feel like creating this effect from scratch, locate User_Drive_Motion.fla in the code archive.

If you don't feel like creating this effect from scratch, locate User_Drive_Motion.fla in the code archive.

设置场景 (Setting the Scene)
Start by creating a new movie that’s 400 pixels wide and 185 pixels high, and has the folder and layer structure shown in Figure 3.10.

Start by creating a new movie that's 400 pixels wide and 185 pixels high, and has the folder and layer structure shown in Figure 3.10.

Figure 3.10. Create the folder structure for the user-driven motion effect.

Figure 3.10. Create the folder structure for the user-driven motion effect.

Create a new movie clip named Animation_Base. In it, place a 190×10 pixel rectangle. Feel free to replace this rectangle with whatever you wish, as we’ll be using it only to illustrate the effect of this animation.

Create a new movie clip named Animation_Base . In it, place a 190×10 pixel rectangle. Feel free to replace this rectangle with whatever you wish, as we'll be using it only to illustrate the effect of this animation.

Drag four instances of the Animation_Base movie clip into the Movie Clips layer, naming them line1, line2, line3, and line4, and positioning them at (10, 10), (10, 20), (10, 30), and (10, 40) respectively.

Drag four instances of the Animation_Base movie clip into the Movie Clips layer, naming them line1 , line2 , line3 , and line4 , and positioning them at (10, 10), (10, 20), (10, 30), and (10, 40) respectively.

Set the Color for each Animation_Base instance to an Alpha value of 0%, so that the clips start off invisible.

Set the Color for each Animation_Base instance to an Alpha value of 0%, so that the clips start off invisible.

Create two new button symbols called Trigger_Show and Trigger_Hide, and create instances of them in the Buttons layer called trigger_show and trigger_hide, respectively. Don’t be too concerned about the way they look – you can redesign them later when you modify the effect for your own use.

Create two new button symbols called Trigger_Show and Trigger_Hide , and create instances of them in the Buttons layer called trigger_show and trigger_hide , respectively. Don't be too concerned about the way they look – you can redesign them later when you modify the effect for your own use.

添加动作脚本 (Adding the ActionScript)

Now, we’ll create a function that will take care of all the movement in this effect, including the speed at which the objects move into and out of position:

Now, we'll create a function that will take care of all the movement in this effect, including the speed at which the objects move into and out of position:

Select the first frame of the Actions layer, and add the following code within the Actions Panel:

Select the first frame of the Actions layer, and add the following code within the Actions Panel:

Example 3.20. User_Drive_Motion.fla Actions : 1 (excerpt)

Example 3.20. User_Drive_Motion.fla Actions : 1 (excerpt)

function MoveTo (clip, fadeType, xTo, yTo, speed) {      clip.onEnterFrame = function ()      {        this._x += (xTo - this._x) * speed;        this._y += (yTo - this._y) * speed;        if (fadeType == "in" && this._alpha < 100)        {          this._alpha += 5;        }        else if (fadeType == "out" && this._alpha > 0)        {          this._alpha -= 5;       co  }      };     }

The MoveTo function accepts the following parameters:

The MoveTo function accepts the following parameters:

clip - The clip we're animatingfadeType - The type of fade effect to display ("in" or "out")xTo - The final horizontal position for the animationyTo - The final vertical position for the animationspeed - The speed of the clip's movement (between 0 and 1 for smooth animation)

Looking over the code, it should be pretty obvious what MoveTo does. It sets up an onEnterFrame event handler for the specified movie that will ease the clip to the specified coordinates while fading its opacity in or out.

The effect will be triggered by the trigger_show button, and reversed by the trigger_hide button. So all we really need to do is call MoveTo with the proper parameter values whenever one of these buttons is clicked.

Adding the Button Trigger Code

Now, we'll add the button trigger code that will make the function work.

Add the following code beneath the function declaration we created in the previous section:

Add the following code beneath the function declaration we created in the previous section: trigger_show.onPress = function () {      MoveTo (line1, "in", 50, 10, 0.3);      MoveTo (line2, "in", 100, 20, 0.3);      MoveTo (line3, "in", 150, 30, 0.3);      MoveTo (line4, "in", 200, 40, 0.3);     };

When the trigger_show button is pressed, the MoveTo function will be called, moving the clips to their new positions. In this example, we move the movie clips horizontally, as the vertical coordinate matches their starting positions on the stage.

When the trigger_show button is pressed, the MoveTo function will be called, moving the clips to their new positions. In this example, we move the movie clips horizontally, as the vertical coordinate matches their starting positions on the stage.

Let's now add the code that will be called when the trigger_hide button is pressed, returning the clips to their resting states:

Let's now add the code that will be called when the trigger_hide button is pressed, returning the clips to their resting states:

Add the following code:

添加以下代码: trigger_hide.onPress = function() {      MoveFromTo(line1, "out", 10, 10, 0.3);      MoveFromTo(line2, "out", 10, 20, 0.3);      MoveFromTo(line3, "out", 10, 30, 0.3);      MoveFromTo(line4, "out", 10, 40, 0.3);     }; Save and preview your work.

保存并预览您的工作。

The effect you see is smooth and crisp. Clicking the first button moves the objects into place, while clicking the second option tucks them away.

The effect you see is smooth and crisp. Clicking the first button moves the objects into place, while clicking the second option tucks them away.

Looks like a menu to me! You could easily build this effect into a navigation element by nesting buttons within the movie clips and altering the passed parameters to suit your needs.

Looks like a menu to me! You could easily build this effect into a navigation element by nesting buttons within the movie clips and altering the passed parameters to suit your needs.

Subtle Flame Animation (Subtle Flame Animation)

With the right balance of subtle animation, you can create effects that are both interesting and visually appealing. In this example, we'll create a realistic flame animation for our hot-rod server (Figure 3.11).

With the right balance of subtle animation, you can create effects that are both interesting and visually appealing. In this example, we'll create a realistic flame animation for our hot-rod server (Figure 3.11).

Figure 3.11. Use random movement to create subtle animation effects.

Figure 3.11. Use random movement to create subtle animation effects.

You can grab the finished version of this example and edit it for your own needs by locating Flaming_Server.fla in the code archive.

You can grab the finished version of this example and edit it for your own needs by locating Flaming_Server.fla in the code archive.

Create a new movie that's 600 pixels wide and 300 pixels high; set the frame rate to 24 fps.

Create a new movie that's 600 pixels wide and 300 pixels high; set the frame rate to 24 fps. Create the layer and folder structure shown in Figure 3.12.

Create the layer and folder structure shown in Figure 3.12.

Figure 3.12. Use this folder and layer structure.

Figure 3.12. Use this folder and layer structure.

Create a background graphic that will serve as the backdrop for the effect within the background layer. In Figure 3.11, I've used a Grand Canyon background.

Create a background graphic that will serve as the backdrop for the effect within the background layer. In Figure 3.11, I've used a Grand Canyon background.

Create a new movie clip named Flame, and create three keyframes. Using the pen tool, create three different flames, one on each keyframe, as shown in Figure 3.13. We'll use these to create the random flame effect.

Create a new movie clip named Flame , and create three keyframes. Using the pen tool, create three different flames, one on each keyframe, as shown in Figure 3.13. We'll use these to create the random flame effect.

Figure 3.13. Create three different flames for a subtle animation effect.

Figure 3.13. Create three different flames for a subtle animation effect.

Drag three instances into the first frame of the Server Animation layer, naming them flame1, flame2, and flame3.

Drag three instances into the first frame of the Server Animation layer, naming them flame1 , flame2 , and flame3 .

Add the following code to the first frame of the Actions layer on the root of the timeline:

Add the following code to the first frame of the Actions layer on the root of the timeline: function randomBetween (a, b) {      return Math.min (a, b) + random (Math.abs (a - b) + 1);     };

What we have here is a useful function that will provide a random integer between the two given numbers (inclusive). Work through the math if you like - Math.min returns the smaller of two numbers, while Math.abs returns the absolute (positive) value of a number. We'll be using this function throughout this example to create additional subtlety and randomness.

What we have here is a useful function that will provide a random integer between the two given numbers (inclusive). Work through the math if you like - Math.min returns the smaller of two numbers, while Math.abs returns the absolute (positive) value of a number. We'll be using this function throughout this example to create additional subtlety and randomness.

Add the following code:

添加以下代码: Flame1.gotoAndPlay (randomBetween (1, 3)); Flame2.gotoAndPlay (randomBetween (1, 3));     Flame3.gotoAndPlay (randomBetween (1, 3));

This randomly starts the animation of each flame between frames one and three.

This randomly starts the animation of each flame between frames one and three.

Now, we have a subtly alternating effect. The next section of code adds a little more randomness - in the real world, flames aren't always the same length. Let's make the size of each flame change at random.

Now, we have a subtly alternating effect. The next section of code adds a little more randomness - in the real world, flames aren't always the same length. Let's make the size of each flame change at random.

Add the following code:

添加以下代码: Flame1.onEnterFrame = function () {      this._yscale = randomBetween (100, 140);      this._alpha = randomBetween (60, 100);     };     Flame2.onEnterFrame = function ()     {      this._yscale = randomBetween (100, 180);      this._alpha = randomBetween (60, 100);     };     Flame3.onEnterFrame = function ()     {      this._yscale = randomBetween (100, 200);      this._alpha = randomBetween (60, 100);     };

This assigns an onEnterFrame event handler to each of the flames. These handlers randomly modify the opacity and vertical scale of the clips for each frame of the animation. Feeding different values to randomBetween gives a different quality to each of the flames.

This assigns an onEnterFrame event handler to each of the flames. These handlers randomly modify the opacity and vertical scale of the clips for each frame of the animation. Feeding different values to randomBetween gives a different quality to each of the flames.

You're done! Preview the movie in Flash.

你完成了! Preview the movie in Flash.

In the completed example that I've created for you, I've put the flame movie clips behind three exhaust pipe graphics and rotated them to make them look realistic when bolted onto the side of a server box, which is a simple graphic symbol.

In the completed example that I've created for you, I've put the flame movie clips behind three exhaust pipe graphics and rotated them to make them look realistic when bolted onto the side of a server box, which is a simple graphic symbol.

结论 (Conclusion)

This chapter has been an adventure in ActionScript animation techniques, and we've covered a lot of ground - from simple animation, to scripted masking and complex duplication techniques. I hope you'll grab the source files from the code archive and rip them apart! Use the techniques that you've learned here to improve your own projects and create new effects.

This chapter has been an adventure in ActionScript animation techniques, and we've covered a lot of ground - from simple animation, to scripted masking and complex duplication techniques. I hope you'll grab the source files from the code archive and rip them apart! Use the techniques that you've learned here to improve your own projects and create new effects.

In Chapter 4, Text Effects, we'll apply these same techniques to create some truly intriguing text effects - effects that really harness the new powers of Flash MX 2004!

In Chapter 4, Text Effects, we'll apply these same techniques to create some truly intriguing text effects - effects that really harness the new powers of Flash MX 2004!

If you can't wait for the next installment, download all three free chapters now.

If you can't wait for the next installment, download all three free chapters now .

翻译自: https://www.sitepoint.com/flash-anthology-3/

actionscript

相关资源:Flash.ActionScript.3.0动画教程.pdf
最新回复(0)