Rotation


Now that we have the ability to move things around the stage in any direction, we need to talk about a related issue. Say that we're making a tank game, and the opponent tank's gun turret rotates to follow the player at all times. We know how to move the opponent 's tank toward the player, but how can we rotate something so that it always faces the player?

The answer lies in the trigonometric functions sine, cosine, and tangent. These three functions are used to relate the lengths of the sides of a triangle to the angles formed by the sides. Because we know where the opponent's tank is and we know where the player's tank is, we can use our trusty right triangle to form the angles between them. All we need to do from there is turn the sides into the angles, which is done with the trigonometric functions I mentioned a moment ago. From that, we can update the tank turret's _rotation property.

But before we dig right into the trigonometric functions, we need to make sure everyone is working with the same units.

Degrees and Radians

You can use several different units when you're measuring an angle. The two units we're going to talk about are degrees and radians. Flash's _rotation property uses degrees, but the trigonometric functions use radians. For that reason, we need to understand both degrees and radians as well as be able to convert between the two. First let's look at exactly what each unit represents.

To talk about angles, it's easiest to use the Cartesian plane again. Assume there is one line segment that goes right down the X axis. Then form a second segment starting at (0,0) and going to any point on the plane. Now an angle has been formed between the two segments, as shown in Figure 8.8.


Figure 8.8: Angles on the Cartesian plane are drawn starting at the X axis. These angles are given in degrees. The angle is usually labeled theta ( ).

What Are Degrees?

You already know a good deal about degrees. You certainly know that a right angle measures exactly 90 degrees. The sum of all three angles in a triangle is 180 degrees, and the angle formed by going once all the way around the origin (a circle) is 360 degrees.

What Are Radians?

Radians are just numbers that represent angles, like degrees. There are 360 degrees in a circle. With radians, there are 2 in a circle. That means that 2 radians = 360 degrees. Therefore, there are radians in a half circle and /2 radian in a right angle.

Converting Between Degrees and Radians

I've already told you that 2 radians are the same as 360 degrees. From that equivalence, we can create an equation that relates the two. Assume that r is the number of radians and d is the number of degrees. Then we have the following equation:

We can solve this equation first for r and then for d. These two solutions give us conversion functions to go from degrees to radians and back again:

The way to approach unit conversion for angles is that the angle in radians must equal the angle in degrees. The problem is that we have a mismatch in the units involved. The first step in making the conversion is to move into a common frame of reference. In this case, I'd like to use half circles. It takes 180 degrees to make a half circle and radians to make a half circle. Keep this in mind as we go to the next step.

In math, you can multiply any number by 1 and have the same number. The interesting thing is that you can write 1 in many ways. 5/5 is 1, as is 10.4/10.4. Also, half circle/half circle is theoretically equal to 1. Earlier, we looked at two ways of describing a half circle: one as radians and the other as 180 degrees. In that way, /180 and 180/ are really both equal to 1 as well.

To put it all together, if we have a number in degrees, we can multiply it by 1 and still have the same value. In this case, though, if we multiply the number of degrees by /180, we get an interesting result. The degree units for our angle and the degree units for the half circle cancel out. The only unit left is radians, which corresponds nicely with the fact that we were looking for the angle in radians. Radian-to-degree conversion is the same, but this time we use 180/ to cancel out the radian units on our angle and leave us with degrees.

We should go ahead and implement these two functions in Flash because we're going to need them. Let's start with the degrees-to-radians function:

 function d2r(d){     return d*Math.PI/180; } 

That's easy enough. We call the method d2r on a degree measure, and it returns the angle measured in radians. Now we need the opposite :

 function r2d(r){     return r*180/Math.PI; } 

The r2d function requires a radian measure and returns the angle measured in degrees.

The Trigonometric Functions

Now we're all set. We have the Pythagorean Theorem, the distance formula, and degrees and radians. Everything we need to talk about trigonometric functions has been covered, so let's dive in.

We can introduce these functions in many ways. I'm going to use a bit of an unorthodox technique to show you how trigonometry works in Flash. I have placed an .fla file (trig.fla) and .swf file (trig.swf) in the Chapter 8 directory of the CD. These files show you an interactive example of what I am about to explain.

Imagine that you have a Cartesian plane and you draw a line from (0,0) to (1,0). It would look something like Figure 8.9.

click to expand
Figure 8.9: A segment drawn from (0,0) to (1,0) can help us visualize the sine and cosine functions.

Now imagine that the segment is fixed at the origin but that you can move the endpoint at (1,0). You can drag that endpoint around the plane in a circle around the origin. This can actually be done in the example trig.swf that I have included on the CD.

As you move the line around the origin, the endpoint that you are dragging changes its coordinates. When you drag it straight up the Y axis, the endpoint coordinates are (0,1). If you drag it back toward the negative X axis, the coordinates are (1,0). If you drag it between the X and Y axes, the X and Y coordinates will be somewhere between 0 and 1.

The actual values of X and Y when you do this are mapped by the sine and cosine functions. If you present an angle to the sine function, it returns the Y coordinate of that line segment when it is drawn with the given angle (the angle between the line and the X axis).

The cosine function, when given the same angle, produces the X coordinate of the line's endpoint.

You can use the trig.swf file to see the exact values of the endpoint as you drag the line around the plane. Figure 8.10 shows this happening.

click to expand
Figure 8.10: As you move the line segment (which always has length of 1) around the origin, the sine of the angle gives the Y value and the cosine gives the X value of the segment's endpoint.

The sine Function

If we plot the changes to the Y value of the line segment's endpoint (from the previous section), we get a plot of the sine function. What used to be the X axis is used to plot the change in the angle, and the Y axis plots the subsequent result from calling sine on that angle. This can be seen in Figure 8.11, and it should be familiar to you.

click to expand
Figure 8.11: The sine wave occurs often in nature.

Notice that the function repeats itself. That repetition in the curve (wave) is called a period. Or more precisely, a period is the distance that a function travels before beginning to repeat itself. In the case of sine, the period is 2

The cosine Function

The cosine function, when plotted, looks identical to the sine function except that it starts at a value of y=1 instead of y=0. Cosine is /2 out of phase with sine. Its plot can be seen in Figure 8.12.

click to expand
Figure 8.12: The cosine function is identical to sine except that it starts at y=1.

As you can see, the period of the cosine function is also 2 .

The tangent Function

Tangent is a bit different from the trigonometric functions we've seen so far. Tangent takes an angle as its argument, like sine and cosine. But it returns the ratio of the sine of that angle to the cosine of that angle, as in the following equation:

The plot of the tangent function can be seen in Figure 8.13.

click to expand
Figure 8.13: The tangent function varies from negative infinity to infinity across the period of .

The period for tangent is , which is half that of sine and cosine's period.

Tangent itself won't be terribly useful to us, but as we'll see in the next section, each trigonometric function has an inverse, and tangent's inverse will be helpful in determining the angle of a line given its x and y constituent elements. Just bear with me another minute and it will all come together.

The Inverse Trigonometric Functions

The trigonometric functions take an angle as their argument and return a value that we can use as a coordinate distance. But what if we want to do the reverse? What if we already know the coordinates and we want to know the angle? This is actually what we need in this case because we are really trying to figure out how to rotate things so that they always face the player. That requires an angle, based on the position of two objects whose coordinates are known.

The inverse trigonometric functions do the opposite of the trigonometric functions. In other words, the arcsine function undoes what the sine function does. This is also true of arccosine and arctangent with cosine and tangent, respectively.

In fact, any inverse function is defined to be the function that undoes what some function does. The following set of functions shows the relationship of the trigonometric functions to each other. In this example, angles are denoted with theta ( ) and lengths are denoted with x:

In Flash, the actual method names are Math.sin , Math.cos , Math.tan , Math.asin , Math.acos , and Math.atan/Math.atan2 .

SOHCAHTOA

Now that we know what the trigonometric functions are, I'm tempted to start using them in Flash to move and rotate things. But before we do that, we need to find a way to get rid of the problem caused by our hypotenuse having a length that is not equal to 1. When the length is 1, the trigonometric functions work great, but when it's not, we have a problem.

Let's go back to our right triangle diagram and take another look (see Figure 8.14). Notice how I've labeled the angle we're talking about as theta ( ) and labeled the sides as opposite, adjacent, and hypotenuse. Those side labels are relative to the angle in question. The side that opposes the angle is called opposite, the side that makes up half of the angle is adjacent, and the hypotenuse is always hypotenuse.

click to expand
Figure 8.14: The sides in a right triangle are labeled relative to the angle we're looking at.

SOHCAHTOA (pronounced so-cah-toe-ah ) is a mnemonic device that tells us the relationship of the sides to the hypotenuse regardless of the lengths of the sides. Here is how it works:

SOH

In other words, the sine of the angle is equal to the ratio of the opposite side to the hypotenuse. SOH should be seen read as "sin is opposite over hypotenuse."

CAH

The cosine of theta is equal to the ratio of the adjacent side to the hypotenuse. CAH should be seen read as "cos is adjacent over hypotenuse."

TOA

The tangent of theta is equal to the ratio of the opposite side to the adjacent. TOA should be seen read as "tan is opposite over adjacent."

So what's really going on here? Did I just pull SOHCAHTOA out of the air? Well, not really. We already knew that the sine of the angle would be the y coordinate ( assuming a hypotenuse length of 1). That's the same as the length of the opposite side. All we're doing is dividing the length of that side by the length of the hypotenuse. That scales the length of the opposite side so that it's correct to the sine function. To illustrate this to yourself, assume the hypotenuse is actually 1 unit long. In that case, sine of theta would be equal to the opposite side over 1, which is just the opposite side, something you already know to be true.

We should take a moment now to consider the tangent function. Remember that it's really a ratio between the sine and cosine of the angle. When we plug in the SOH and CAH parts of SOHCAHTOA into the tangent function, we get the following equation:

From that equation, the hypotenuse can be removed because anything over itself reduces to 1. We are left with the tangent function from SOHCAHTOA.

What is SOHCAHTOA good for? Well, if you know the length of one side and you know an angle, you can use SOHCAHTOA to find the length of the unknown side.

But that's not what this whole discussion is about, is it? We know the lengths of the sides, and we're looking for the angle so that we can properly rotate our graphic. It's time to bring back the inverse trigonometric functions.

Remember that arcsine did the opposite of sine? When I gave equations for this (refer to "The Inverse Trigonometric Functions" section), I used theta for the angle and x for the length. Well, we can use the equations for SOHCAHTOA in place of x in those inverse equations to generate the following set of equations:

As you can see, these three equations can be called on the lengths of the sides to produce the angle theta. Therefore, the three inverse trigonometric functions are our ticket to finding angles based on the positions of the objects. All we have to do is rewrite these equations into code Flash can understand, and we can solve the rotation problem.

Implementing Rotation in Flash

We're finally ready to solve our problem. We have a movie clip and we want it to constantly rotate to face the mouse, wherever the mouse moves to. You already know we're going to be using the inverse trigonometric functions, but which ones and on what? The answer is that it is somewhat application dependent, but the majority of the time it works like this.

You want to rotate object A so that it always faces object B. In this situation, you know the position of both objects ”that is, you know their X and Y coordinates. That means you know the length of the opposite and adjacent sides. You can, of course, find the length of the hypotenuse by using the distance formula, but that is not necessary. With the opposite and adjacent sides at your disposal, you can use the arctangent function. Remember that arctangent of the opposite side divided by the adjacent side is equal to the angle formed by the line between them and the X axis. So consider this implementation:

 function faceMouse(o){     o._rotation = Math.atan((o._y-_ymouse)/(o._x-_xmouse)); } 

This should set the rotation to face the mouse using arctangent. However, if you test it, it doesn't work correctly. That's because the rotation property is in degrees and the trigonometric functions use radians. We need to convert. Consider this implementation:

 function faceMouse(o){     o._rotation =  r2d(  Math.atan((_ymouse-o._y)/(_xmouse-o._y))  )  ; } function r2d(r){     return r*180/Math.PI; } 

Now we're using our r2d function to convert the radian measure to degrees. However, if you test this, you find that it's still not working correctly. The object faces the mouse when the mouse is to the right of the object, but the object faces directly away from the mouse when the mouse is to the left of the object. That's because the period of tangent is only half as long as that of sine and cosine. There is a built-in Math function that eliminates that problem. It's called atan2 and it has the following general form:

 Math.atan2(  x  ,  y  ); 

In atan2 , x and y are the coordinates of the object to face. In other words, they are the top and bottom of the division that we sent to Math.atan in the previous implementation. Consider this final implementation:

 function faceMouse(o){     o._rotation = r2d(  Math.atan2(o._y-_ymouse, o._x-_xmouse)  ); } 

Notice that instead of a division, we're sending in the side lengths as individual arguments. The atan2 function handles them properly and our resulting angle is correct.

That's about as far as I want to go into the subject of trigonometry. We could spend several chapters talking about things we can do with it ”including simulating 3D effects ”but that would get us somewhat off track. What we've covered so far is sufficient to give you an idea of how trigonometry works and how you can use it to move and rotate objects in your game.

Caution  

If your symbol's art does not face toward the right, you must either rotate it manually or add 90 degrees to the object's rotation if the object is pointing up. That's because a 0-degree angle implies pointing down the X axis, not pointing straight up as your intuition might tell you.

Trigonometry on Any Triangles

I do want to mention one last thing because I hate to leave the subject of trigonometry without at least touching on this point.

So far, all the trigonometry we've done has been on right triangles. Things are simple that way, but the trigonometry functions are more powerful that that. You can use trigonometry to find the relation of sides to angles in any triangle, whether it's right, obtuse, or acute. The equations for doing this are listed in any advanced algebra book, so I won't be covering them here. You can find links to some trigonometry tutorials in Appendix D, "Web Resources and Further Reading."




Macromedia Flash MX 2004 Game Programming
Macromedia Flash MX 2004 Game Programming (Premier Press Game Development)
ISBN: 1592000363
EAN: 2147483647
Year: 2004
Pages: 161

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