*Introduction to 3D Game Programming with DirectX 9.0c: A Shader Approach*.

You may remember from your high school Trigonometry class (don't worry if not, it was a long time ago for me too!) those two periodic functions, sine (pronounced "sign") and cosine ("co-sign"). They're essentially the same function and you could map one to the other with a slight shift. Cosine has some unique applications of its own, such as determining light intensity based on viewing angle, but the demos below will focus primarily on sine waves.

Notice a few interesting properties from the graph above. One is that a sine wave repeats itself every 2π (π ≈ 3.14159) or 360 degrees along the X-axis. Another is that it oscillates between the Y values -1 and 1. We write the function

**y = sin(x)**to indicate the Y value as a function of X; see from the graph above that Y = 0 when X is any multiple of π and Y is either 1 or -1 (the peaks and valleys) when X is an odd multiple of π/2.

**Point Light Demo - Download Program!**

This demo shows how sine waves can be used to animate a light source. Use the specified keys to combine waves, creating a variety of unique horizontal and vertical motion paths.

Before learning this elegant method, my approach to animating an object that sways back and forth, or moves repeatedly up and down along a pole, was to use code like this in my update loop:

static bool moveUp = true; if (moveUp) { if (shipPos.y < 100) shipPos.y += value; else moveUp = false; } else { if (shipPos.y > -100) shipPos.y -= value; else moveUp = true; }

**shipPos.y = 100 * sin(x)**! Notice that I multiplied by 100 to get the desired range instead of the standard oscillation from -1 to 1.

**Ocean Waves Demo - Download Program!**

This demo illustrates the effects of adding sine waves and two different wave types, circular and directional. Use the specified keys to play with parameters and change the wave patterns.

As with the Point Light demo, you will need to have DirectX (from Windows Update) installed in order to run the program.

These are just a couple applications of the sine function. Because of its periodic repetition, it could have many potential uses; some fellow GCG forum members cited their implementations of a 3D carousel and a wavy spaceship flight path as additional examples.

I hope you enjoy the demo programs of this post, though I admit I still need to learn better methods of input handling. Part two will describe wave alterations, based on the Ocean Waves demo, in greater detail. Until then, feel free to let us know:

**What's the coolest thing you've done with sine/cosine waves?**

Great post! Very informative.

ReplyDelete