< Day Day Up > |
The trigonometric functions often surface in game programming. Any time you model a scenario with a right triangle (which happens often on a gridlike screen), the trig functions come in handy. We'll also use them in the vector chapter (Chapter 4) and again in all the 2D and 3D physics chapters. In addition, we'll look at the graphs of sine and cosine, because they can be used for any kind of oscillating (wavelike) motion. But before we get too carried away, let's define these functions from scratch. The trigonometric functions are all defined in terms of a right triangle; they're really just relationships between two of the three sides. Look at the triangle shown in Figure 3.4. It's a right triangle, so you can use it to define sine, cosine, and tangent. Figure 3.4. A right triangle.
Notice that angle a is labeled. It is important to always indicate which angle the function is taking as input. The trig functions are useless without an angle as input. In this case, use a to set up the definitions of sine (sin), cosine (cos), and tangent (tan).
NOTE These trig functions apply only to a right triangle. They will not work for any other type of triangle. As you can see, sine, cosine, and tangent are simply fractions, or ratios, relating two out of the three sides of the right triangle. The reference angle determines which sides to use. Notice that if you use the other nonright angle, that switches which side is opposite and which side is adjacent, so always include the reference angle. Example 3.5: Defining Sine, Cosine, and TangentIf a is an angle in standard position, and (12,5) is a point on its terminal side, find sin a , cos a , and tan a . Solution
There are actually six trigonometric functions total. We've already defined the first three in terms of the triangle shown in Figure 3.4. The other three functions, cosecant (csc), secant (sec), and cotangent (cot), are simply reciprocals of the first three.
Because these last three functions are simply reciprocals, most of the time all you need are the first three: sine, cosine, and tangent. However, there might be times when you simplify a formula and you end up with a fraction involving sine, cosine, or tangent. In those special cases, it might further optimize your code to use one of these last three functions instead. Even though these trigonometric functions sound intimidating, they're really just functions that have been preprogrammed into your calculator. You can access them using buttons , just like the multiply function or the square root function. If you have a scientific calculator, take a minute to familiarize yourself with its trig functions. If you have Windows installed on your computer, it comes with a calculator on the Accessories menu. If you switch the View to scientific, you'll see that the trig functions appear on the left side. Type in 30 , and then click the sine button. You should get 0.5. Notice that you can also switch to radian mode at the top and enter the angle in radian mode if you want. Most scientific calculators give you that option. You might want to practice using your calculator with some of the frequently used angles shown in Table 3.1. Table 3.1. Trigonometric Functions for Frequently Used Angles
Many programmers prefer to create a look-up table for trigonometric functions before the actual game loop begins to run. This can greatly increase the speed at which trig values can be calculated in code. An example of creating a look-up table follows : // This will hold our values float sin_table[360]; // Fill in our table for(int i = 0; i < 360; ++i) { // Remember our DegToRad #define from before, PI / 180 sin_table[i] = sin(i * DegToRad); } Having created this sin table, the program no longer needs to call upon the sin() function to calculate the value, but would rather look it up in this way: // Calculate the sine of any angle float value = sin_table[abs((int)angle) % 360]; By typecasting the angle to an int, then getting its absolute value and using the modulus operator, we ensure that regardless of the size of our angle, we won't be blowing out of our array bounds. It is also important to note, however, that if the #pragma intrinsic command is used to make the trig functions intrinsic in a Microsoft compiler, the amount of optimization created by using a look-up table becomes virtually negligible. #pragma intrinsic(sin, cos, tan) NOTE Check your MSDN library for a list of compiler switches which need to be turned on in order to make the trig functions intrinsic. Also be warned that the intrinsic commands cannot be used on these functions while in debug mode, so only use this option when you are ready to create your final release build. Let's look at a couple examples to see how these trigonometric functions are actually used. Example 3.6: Using CosineSuppose your game character shoots an arrow at a target in the air. He's aiming at a 60 angle, and the arrow follows a straight-line path for 50 pixels. If the sun is directly overhead, how far must the shadow travel across the ground? Solution
This means that the shadow must travel 25 pixels across the ground. Notice that when you know the angle, you use the regular cosine function in the calculator. The calculator actually returns the value of the ratio (adjacent/hypotenuse) for that angle. What if you were working backwards ? That is, what if you know the fraction and you want the angle measure? This requires using the inverse of one of the trigonometric functions. The inverse is written with a 1 superscript, and the letters "arc" are placed in front of the name . For example, the inverse cosine function is written cos 1 and is pronounced " arccosine ." Many calculators use the 2nd function or the Shift key for the inverses. Check your calculator to find them. The Windows calculator has a check box for the inverse function. Let's revisit the shooting-arrow example for practice with the inverse function. Example 3.7: Using the Inverse TangentSuppose your game character shoots an arrow at a target in the air. He's standing 100 pixels away from the target, which is 400 pixels off the ground. What angle should he aim at if the arrow will follow a straight-line path? Solution
This means that the player must aim at a 76 angle in standard position to hit the target. Let's find out how to solve a similar problem in code by using a function which will return the angle between two objects in standard position, given their locations: // purpose: to calculate the angle between 2 objects in 2D space // input: P1 - the location of the first object // P2 - the location of the second object // output: the angle between the objects in degrees float calcAngle2D(float *P1, float *P2) { // Calculate our angle float ang = (float)atan((P2[1] P1[1]) / (P2[0] P1[0])) * RadToDeg; // In the event that the angle is in the first quadrant if(P2[1] < P1[1] && P2[0] > P1[0]) return ang; // In the event of second or third quadrant else if((P2[1] < P1[1] && P2[0] < P1[0]) (P2[1] > P1[1] && P2[0] < P1[0])) return ang + 180; // If none of the above, it must be in the fourth else return ang + 360; } Of importance in this function is the means through which we figure out the actual angle based on the returned value of atan() . Remember that the sine of angles is positive in the first and second quadrants, the cosine of angles is positive in the first and fourth quadrants, while the tangent of angles is positive in the first and third quadrants. All the inverse trig functions will always return the angle in the first quadrants if passed in a positive value. If passed in a negative value, however, asin() and atan() will return the angle in the fourth quadrant, while acos() will return the angle in the second quadrant. Therefore in this example, we must check the object's positions in relation to themselves to see which quadrant our angle is truly in, and then add either 180 or 360 to get that angle in standard position. NOTE When you know the angle measure, use the regular sine, cosine, or tangent function. If you want to return the angle, use one of the inverse functions. The last thing this section needs to address is the graph of sine and cosine. You might have seen a sound wave before; that's exactly what the graphs of sine and cosine look like. First, you'll examine the graph of y =sin( x ), and then you'll compare it to the graph of y =cos( x ). You can use Table 3.1 to plot a couple reference angles to get started. If you use the angle in degrees column for the x values, the sin a column would represent the corresponding y values. If you used your calculator for the sine of some of the angles in between, you'd find that they all fall on the curve graphed in Figure 3.8. Figure 3.8. Graph of y=sin(x).
Notice that the graph has a pattern that repeats every 360 (or 2 p R ); this is called the fundamental period . There are ways to alter the period if you need to stretch or squish the graph horizontally to fit your needs. To change the period, simply place a number in front of the x . Fractions stretch the graph, and larger numbers compact it. Example 3.8: Stretching the Sine Wave HorizontallyGraph the equation y =sin(1/2 x ). Solution
Example 3.9: Squishing the Sine Wave HorizontallyGraph the equation y =sin(2 x ). Solution
Look back at the last two examples. Notice that when you place in front of the x , the sine wave repeats every 720 instead of every 360. Then, when you place a 2 in front of the x , the pattern repeats every 180. This leads to the first characteristic of the sine wave.
NOTE The period measures how often the sine wave repeats. We put the absolute value symbol around B because a negative sign would not affect the period. Also note that if there is no number in the B position, B =1, which brings us back to the fundamental period of 360. You can also stretch or squish the sine graph vertically by placing a number in front of the sine function, which changes the amplitude . This time a fraction squishes the graph, and a large number stretches it. Be careful, because this is the opposite of the period. Example 3.10: Stretching the Sine Wave VerticallyGraph the equation y =2sin x . Solution
Example 3.11: Squishing the Sine Wave VerticallyGraph the equation y =sin x . Solution
Notice that the sine wave normally fluctuates between 1 and 1. When you place a 2 in front of the sine, the graph goes as high as 2 and as low as 2. Then, when you place in front of the sine, the graph cycles between and . This leads to the second characteristic of the sine wave.
NOTE The amplitude measures how high and low the sine wave fluctuates. We put the absolute value symbol around A because a negative sign would not affect the amplitude. You might want to use a small amplitude for something like the motion of a ship on the water. These same two characteristics apply to the cosine function in exactly the same way. The only difference is that the cosine function is offset to the left by 90. Figure 3.13 shows the graph of y =cos x . Notice that the highest point crosses at the y-axis rather than at 90. Everything else is identical, just shifted 90 to the left. Figure 3.13. Graph of y=cos(x).
This section has defined all six trigonometric functions. These functions can now be used in our study of vectors in the next chapter. They can also be used whenever you model a situation with a right triangle or whenever you want an object to follow a wavelike motion path. Self-AssessmentUsing your calculator, find the value of the following trigonometric functions:
State the period and amplitude of the following equations:
|
< Day Day Up > |