Velocity

The most basic property of something that is moving is velocity. Many people equate the term velocity with speed. Thats part of it, but only part. The concept of velocity contains a very important second factor: direction . And that is pretty much our laymans definition for velocity: speed in a particular direction. Lets take a look at exactly how this definition differs from simple speed.

If I tell you that I got in my car at point X and drove 30 miles per hour for one hour, youd have a pretty hard time finding me. On the other hand, if I said I drove due north for one hour at the same speed, youd know precisely where I was. This is pretty important in animation, because you need to know where to put movie clips. Its fine to say a movie clip is moving at a certain speed, but youre going to need some specific x, y coordinates to assign to it on each frame to give it the illusion of motion. This is where velocity comes in. If you know where something is at the start of a particular frame, how fast it is moving, and in what direction, you know where to put it at the start of the next frame.

The speed part of it is usually defined in terms of pixels per frame (ppf). In other words, if a movie clip is at a certain point as it enters a frame, its going to be so many pixels away from that point at the end of the frame.

In most cases, using pixels per frame works fine, and it is definitely the simplest to program. However, due to the unstable nature of frame rates in Flash, using pixels per frame may make your animation slow down at certain points when too much is happening, there is too much to compute, or the CPU is busy doing something else. If you are programming some kind of game or simulation in which it is crucial that the animation proceeds at a very uniform rate, you might want to use an interval-based animation instead. Ive included an example of that approach in Chapter 19.

Before getting into coding velocity, I want to talk a little bit about vectors, as thats how velocity is generally depicted.

Vectors and velocity

A vector is something that has magnitude and direction. In the case of velocity, the magnitude is the speed. Vectors are drawn as arrows. The length of the arrow is its magnitude, and the direction the arrow is pointing in is, naturally, the direction of the vector. Figure 5-1 shows some vectors.

image from book
Figure 5-1: A few vectors

One thing to note is that the magnitude is always positive. A vector with a negative magnitude would simply be a vector going in the opposite direction, as illustrated in Figure 5-2.

image from book
Figure 5-2: Negative velocity is really velocity in the opposite direction.

Another thing to note is that vectors dont really have any set position. Even in the case of velocity, the vector doesnt state where something is starting or where it ends up; it just indicates how fast and in which direction the object is moving. Thus, two vectors can be equal if they have the same direction and magnitude, even if they are describing two different objects in two different locations, as shown in Figure 5-3.

image from book
Figure 5-3: If vectors have the same magnitude and direction, they are the same. Position doesnt matter.

Velocity on one axis

Im going to simplify things at first, by limiting velocity to a single axis: the x axis, or horizontal motion. This is basically saying that the direction is zero degrees, due east, or from the left side of the screen to the right side of the screenhowever you want to look at it. The speed is just how many pixels it moves in that direction each frame. Thus, if I say that the velocity on the x axis is 5, I mean that the object will move 5 pixels each frame from left to right. This also means that if I say the velocity is ˆ 5 on the x axis, it will move right to left, 5 pixels each frame.

Now, you caught me there, didnt you? Already Im talking about a negative magnitude when I just told you theres no such thing. Technically speaking, the velocity would actually be 5 and the direction 180 degrees. Similarly, a positive y velocity would be that speed at 90 degrees (straight down), and a negative y velocity would be 270, or ˆ 90 degrees (straight up). In practice, though, when you are calculating component x, y velocities, they always come through as positive and negative numbers , and you are often going to see me writing things like, the x velocity is ˆ 5. So, if it helps you, think of the minus sign as indicating to the left for x velocity or up for y velocity, rather than meaning negative.

Throughout the book, I will use vx to stand for velocity on the x axis, and vy to mean velocity on the y axis. Positive vx means to the right, and negative vx means to the left. Positive vy means down, and negative vy means up.

For velocity on one axis, you simply add the velocity to the objects position on that axis. Whatever your vx is, you add it to the objects _x property on each frame.

Lets see it in action. The first few examples in this chapter will use a similar setup as the chapter2base.fla you used in Chapter 2. Youll use an FLA file with a single movie clip symbol in the library, named ball and exported with the same linkage name . For each example, Ill give you code to put on frame 1 of the main timeline. Heres the first example, which you can find in ch05_01.fla :

 init(); function init():Void {       vx = 5;       ball = attachMovie("ball", "ball", 0);       ball._x = 0;       ball._y = Stage.height / 2; } function onEnterFrame():Void {       ball._x += vx; } 

In this example, first you set an x velocity ( vx ) of 5. Remember that is 5 pixels per frame, so on each frame, the vx is added to the _x property. Then it goes through the business of getting the ball out of the library and onto the stage, and setting up the event handler for the enterFrame event. On each frame, the ball will be placed 5 pixels to the right of where it was on the last frame. Try it out. Pretty good illusion of motion, eh?

Play around with it. Give it higher values or lower values for vx . Try some negative values and watch it move in the other direction. See if you can make it move on the y axis instead.

Velocity on two axes

Moving along two axes is pretty simple. You just define a vx and a vy , and then add the vx to the _x property and the vy to the _y property on each frame. So, what you are saying is that for each frame, the object is going to move so many pixels on the x axis and so many pixels on the y axis.

The next example ( ch05_02.fla ) demonstrates this, and here it is:

 init(); function init():Void {       vx = 5;       vy = 5;       ball = attachMovie("ball", "ball", 0);       ball._x = 0;       ball._y = Stage.height / 2; } function onEnterFrame():Void {       ball._x += vx;       ball._y += vy; } 

Again, play around with the velocity variables until you get a good feel for them. Dont forget to try out some negative values.

Angular velocity

OK, so far, so good. You have some real animation going on, using velocity on two axes. But in many casesmaybe most casesx and y velocity wont be the initial data you have.

The fact is Im kind of cheating with the definition of velocity here. I said its speed in a direction, but now Ive given you two different speeds in two different directions. The reason I did that is because, in Flash, you position objects by placing them on x, y coordinates. So you need to end up with a velocity and position on both axes, but thats not necessarily what you start out with.

What if you just have a value for speed and an angle for direction, per the definition. Say you want something to move at an angle of 45 degrees and a speed of 3 pixels per frame. I dont see any vx or vy , or anything even similar in that description.

Fortunately, youve already been introduced to the tools you need to derive vx and vy from that description. Think back to the discussion of trigonometry in Chapter 3. Now, look at Figure 5-4, which shows what you want the ball to do on each frame: move 3 pixels at an angle of 45 degrees.

image from book
Figure 5-4: A magnitude and a direction

Does this diagram look familiar? How about if I add another line, as shown in Figure 5-5? What do you know? You have a right triangle, with one angle and the hypotenuse defined!

image from book
Figure 5-5: Magnitude and direction mapping becomes a right triangle.

Notice that the two legs of that triangle lie on the x and y axes. In fact, the leg that lies on the x axis is equal to the distance the ball is going to move on the x axis. The same goes for the leg on the y axis. Remember that in a right triangle, if you have one side and one angle, you can find all the rest. So, given the 45 degrees and the hypotenuse of 3 pixels, you should be able to use Math.cos and Math.sin to find the lengths of vx and vy .

The side adjacent to the angle is vx . The cosine of an angle is the adjacent/hypotenuse. Or, stated another way, the adjacent side is the cosine of the angle times the hypotenuse. Similarly, the opposite side is vy . Sine is opposite/hypotenuse, or the opposite is the sine times hypotenuse.

Heres the exact code you would use:

 vx = Math.cos(angle) * speed; vy = Math.sin(angle) * speed; 

Now dont you dare forget to convert the 45 degrees to radians before passing it into the Math functions! Once you have the vx and the vy , you can easily add these to the x, y position of the object you are animating.

The next example ( ch05_03.fla ) has the following code on frame 1:

 init(); function init():Void {       angle = 45;       speed = 3;       ball = attachMovie("ball", "ball", 0);       ball._x = Stage.width / 2;       ball._y = Stage.height / 2; } function onEnterFrame():Void {       var radians:Number = angle * Math.PI / 180;       var vx:Number = Math.cos(angle) * speed;       var vy:Number = Math.sin(angle) * speed;       ball._x += vx;       ball._y += vy; } 

The main difference here is that youre starting off with angle and speed rather than vx and vy . The velocities are calculated as local variables, used, and discarded. Of course, in a simple case like this, where the angle and speed are never changing, it would make more sense to calculate the velocities once and save them as timeline variables. But in most advanced motion, both the direction and speed of motion will be constantly changing, so the vx and vy will not remain static.

To experiment with this example, change the angle around. See for yourself that you can make the ball travel at any speed and any angle by simply changing those two numbers.

Now, lets take another look at this example in terms of vectors.

Vector addition

Vector addition is when you have two vectors working in a system and you want to find the resultant overall vector. Here, you have a vector on the x axis, another vector on the y axis, and an overall velocity vector. You add vectors by simply placing them together head to tail. The resultant vector is the line you can draw from the starting point of the first vector on the chain to the ending point of the last one. In Figure 5-6, you can see three vectors being added together and their resultant vector.

image from book
Figure 5-6: Vector addition

It doesnt matter in what order you place the vectors; the result will always be the same. And time has no part in it. You could say an object moved this way, then it moved that way, and then it moved the other way, in any order. Or you could say that it moved in all three ways at once. The result is that it wound up moving at a certain speed in a certain direction when all was said and done.

Lets go back to our example. If you lay down the x-axis velocity vector, and then put the y-axis velocity vector on the end of that, the resulting line is the overall velocity. Figure 5-7 illustrates the velocities as vectors.

image from book
Figure 5-7: Velocities as vectors

What do you know? Its the same picture! Take that as a sign that you are doing something right.

A mouse follower

Lets use the velocity concepts to expand on an earlier concept. Back in Chapter 3, you built an example with an arrow that always pointed to the mouse. That example used Math.atan2 to compute the angle between the mouse and the arrow movie clip, and then rotated it so it lined up with that angle. With what you just learned, you can now throw some speed into the mix and get a velocity based on the current angle. This example uses the same arrow movie clip, rather than the ball. Here is the code for it ( ch05_04 ):

 init(); function init():Void {       speed = 5;       arrow = attachMovie("arrow", "arrow", 0);       arrow._x = Stage.width / 2;       arrow._y = Stage.height / 2; } function onEnterFrame():Void {       var dx:Number = _xmouse - arrow._x;       var dy:Number = _ymouse - arrow._y;       var angle:Number = Math.atan2(dy, dx);       arrow._rotation = angle * 180 / Math.PI;       var vx:Number = Math.cos(angle) * speed;       var vy:Number = Math.sin(angle) * speed;       arrow._x += vx;       arrow._y += vy; } 

While this is a pretty complex effect, there shouldnt be anything in here that you dont fully understand by now. Youre getting the x distance and y distance to the mouse, and from that using Math.atan2 to get the angle that forms. Youre then using that angle to rotate the arrow, and using Math.cos and Math.sin along with the speed to find the x and y velocities. Finally, youre adding the velocities to the position.

Velocity extended

Im entering into dangerous territory here, but Im going to start taking the definition of velocity into places it was never meant to go. While, in a strict sense, velocity refers to change of position and physical motion through space, theres no need to limit the concepts youve just learned to just the _x and _y properties of movie clips.

A movie clip has a lot of properties you can tinker with, and almost all of them can accept a wide range of values that you can change over time to produce animation. Perhaps velocity isnt the correct word for it, but the concept is similar, and this is the ideal place to talk about these other properties. Due to the similarities, I often continue to use the word velocity in my variable names far more often than I should.

An example would be having a movie clip spin around. In this case, you are changing the objects _rotation property on each frame by adding a value to it. You can make it spin quickly by adding a high value to the _rotation property on each frame, or have it spin more slowly by adding a smaller value. Correct or not, I usually refer to the variable that holds the spinning speed as vr , for rotational velocity.

Using the familiar arrow movie clip, you can come up with something like this ( ch05_05.fla ):

 init(); function init():Void {       vr = 5;       arrow = attachMovie("arrow", "arrow", 0);       arrow._x = Stage.width / 2;       arrow._y = Stage.height / 2; } function onEnterFrame():Void {       arrow._rotation += vr; } 

In terms of velocity here, the speed is 5 and the direction is clockwise. I might even get away with that one, as theres still some motion going on, but when I start using terms like alpha velocity (how fast something is fading in or out), Im sure Ill ruffle some feathers. Still, I find it useful to think of such properties in these same terms. I want to change the alpha at a certain rate by adding or subtracting to its value on each frame. As I often find myself changing several properties over time, each at certain rates, its nice to relate them all by calling them velocities. Thus, I might wind up with something like this:

 function onEnterFrame():Void {    arrow._x += vx;    arrow._y += vy;    arrow._alpha += vAlpha;    arrow._rotation += vr;    arrow._xscale = arrow._yscale += vScale;    // etc. } 

Youll see a lot of examples like this later in the book, so I hope youll forgive my occasional v .

That about does it for velocity and its cousins. Now, lets move on to acceleration.



Foundation ActionScript. Animation. Making Things Move
Foundation Actionscript 3.0 Animation: Making Things Move!
ISBN: 1590597915
EAN: 2147483647
Year: 2005
Pages: 137
Authors: Keith Peters

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net