Beginning Math and Physics for Game Programmers

 < 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).

where opp = the side opposite a , adj = the side adjacent to a , and hyp = the hypotenuse .

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 Tangent

If 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

  1. To talk about the trig functions, we need to establish a right triangle. Figure 3.5 shows a right triangle created using the point (12,5) on the terminal side.

    Figure 3.5. A right triangle for Example 3.5.

  2. The coordinates of the point (12,5) give you the length of two sides. You can use the Pythagorean theorem to calculate the length of the third side:

  3. Now all you have to do is apply the definitions of sine, cosine, and tangent:

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.

Other Trigonometric Functions

where opp = the side opposite a , adj = the side adjacent to a , and hyp = the hypotenuse.

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

a (Degrees )

a (Radians )

sin a

cos a

tan a

1

30

p /6

0.5

0.8660

0.5774

45

p /4

0.7071

0.7071

1

60

p /3

0.8660

0.5

1.7321

90

p /2

1

120

2 p /3

0.8660

0.5

1.7321

180

p

1

270

3 p /2

1

360

1

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 Cosine

Suppose 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

  1. This scenario can be modeled with a right triangle. Place the angle in standard position, and label the hypotenuse with a length of 50 pixels, as shown in Figure 3.6.

    Figure 3.6. A right triangle for shooting an arrow.

  2. You can see that you're actually looking for the length of the bottom side of the right triangle. Call it a .

  3. The cosine function sets up a relationship between the adjacent side a and the hypotenuse, so use that:

    50 (cos 60) = a

  4. Using the Windows calculator, type in the angle: 60 . Then click the cos button. This should give you 0.5. Last, multiply that by the 50 pixels, which gives you 25.

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 Tangent

Suppose 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

  1. This scenario can be modeled with a right triangle. This time, you know the lengths of the two sides, as shown in Figure 3.7.

    Figure 3.7. Another right triangle for shooting an arrow.

  2. This time you're looking for the angle in standard position. Call it a .

  3. The tangent function sets up a relationship between the opposite side and the adjacent side, so use that:

  4. Using the Windows calculator, type in the ratio of the opposite side divided by the adjacent side: 4 . Click the Inv (inverse) check box. Then click the tan button. This should give you approximately 76.

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 Horizontally

Graph the equation y =sin(1/2 x ).

Solution

  1. The easiest way to start is to plug in several x values and calculate the corresponding y . Table 3.2 shows a few key points.

    Table 3.2. Points on y=sin(1/2x)

    X

    y

    180

    1

    360

    540

    1

    720

  2. After you've plotted these key points, try plugging in a few more. You'll find that they all fall in the curve shown in Figure 3.9.

    Figure 3.9. Graph of y=sin(1/2x).

Example 3.9: Squishing the Sine Wave Horizontally

Graph the equation y =sin(2 x ).

Solution

  1. The easiest way to start is to plug in several x values and calculate the corresponding y . Table 3.3 shows a few key points.

    Table 3.3. Points on y=sin(2x)

    X

    y

    45

    1

    90

    135

    1

    180

  2. After you've plotted these key points, try plugging in a few more. You'll find that they all fall in the curve shown in Figure 3.10.

    Figure 3.10. Graph of y=sin(2x).

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.

Period of the Sine Wave

For y =sin( Bx ), the period = .

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 Vertically

Graph the equation y =2sin x .

Solution

  1. The easiest way to start is to plug in several x values and calculate the corresponding y . Table 3.4 shows a few key points.

    Table 3.4. Points on y=2sinx

    X

    y

    90

    2

    180

    270

    2

    360

  2. After you've plotted these key points, try plugging in a few more. You'll find that they all fall in the curve shown in Figure 3.11.

    Figure 3.11. Graph of y=2sin(x).

Example 3.11: Squishing the Sine Wave Vertically

Graph the equation y =sin x .

Solution

  1. The easiest way to start is to plug in several x values and calculate the corresponding y . Table 3.5 shows a few key points.

    Table 3.5. Points on y=sinx

    x

    Y

    90

    180

    270

    360

  2. After you've plotted these key points, try plugging in a few more. You find that they all fall in the curve shown in Figure 3.12.

    Figure 3.12. Graph of y=sin(x).

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.

Amplitude of the Sine Wave

For y = A sin( x ), the amplitude = A .

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-Assessment

Using your calculator, find the value of the following trigonometric functions:

1.

sin 45

2.

cos 125

3.

tan 35

4.

Find sin a , cos a , and tan a for the angle shown in Figure 3.14.

Figure 3.14. A right triangle for question 4.

5.

Find the degree measure of angle a in Figure 3.14.

6.

Find cot 35.

7.

Find csc 20.

8.

Find sec 45.

State the period and amplitude of the following equations:

9.

y =5sin3 x

10.

y =3cos x

11.

y =cos4 x

12.

y =5sin x

13.

y =2cos( x )

14.

y = sin(2 x )

 < Day Day Up > 

Категории