Game Development Reference
In-Depth Information
The default values describe a graph positioned at
x:-100, y:-100
with each
axis being 200 pixels long. This will make the graph big enough to easily read, but
the
DrawGraph
function treats the graph as if the x and y axes run from 0 to 1.
After the member variables, a delegate is defined.
public delegate double WaveFunction(double value);
f(x
0
) where x
0
is the next value of x and
plain x is the previous value. The x value is usually increased by a set number and
the y value is calculated from the x. The
WaveFunction
delegate describes f in
the formula; a function that takes in some double value and returns some double
value. This is the same signature of the cosine and sine functions. By using a
WaveFunction
type, the
DrawGraph
function can take in cosine, sine, or any
other wave function and no extra code needs to be written.
x
0
,y
Graphs are often defined as x
¼
¼
The state's constructor sets the line width to 3 pixels making the graph lines easy
to see. It also turns off the texture state; if the texture state is turned on, the lines
may appear dull because they are incorrectly being assigned an invalid texture.
The
DrawGraph
function is the most important function in the game state. It is
responsible for plotting the graph. It uses the sample rate to work out how to
space the vertices so that any line will totally fill the length graph. There are two
common ways to define angles: degrees and radians. Degrees are quite com-
monly known; a full circle is 360
, and a half circle is 180
. Radians are a mea-
surement of degrees using Pi, a full circle is two times Pi, and a half circle is Pi.
The C#
Sin
and
Cos
functions expect to be given an angle in radians; for this
reason, the 0-1 value of the X axis is scaled by Pi when the Y axis values are being
calculated.
The inner loop of the
DrawGraph
function works out a new position from the
old position and then plots a line from the old position to the new position. To
demonstrate the code in action, a
Render
function needs to be written that calls
DrawGraph
for sine and cosine. The graph output can be seen in Figure 8.1.
public void Render()
{
DrawAxis();
DrawGraph(Math.Sin, new Color(1,0,0,1));
DrawGraph(Math.Cos, new Color(0, 0.5f, 0.5f, 1));
}
Search WWH ::
Custom Search