Game Development Reference
In-Depth Information
create a new game state and make this the activate state to test the code. All the
example code is available on the CD in the Code\Chapter 8 directory. The next
sections will explain the various vector operations and list the code that needs to
be added to complete the vector class. Game engines sometimes have a Vector2d,
Vector3d, and Vector4d, but I think it's simpler in this case to just have one
vector structure; it can still be used for any 2D operations, and for the contents of
this topic, 4D vectors won't be used.
[StructLayout(LayoutKind.Sequential)]
public struct Vector
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public Vector(double x, double y, double z) : this()
{
X=x;
Y=y;
Z=z;
}
}
The Length Operation
The length operation takes a vector and returns that vector's magnitude. With
a simple vector of [0, 1, 0], it's easy to see the length is 1, but with a vector of
[1.6, -0.99, 8], the length is less apparent. Here is the formula to give a vector's length.
p
x 2
jj v jj ¼
þ y 2
þ z 2
The two bars around the v are the mathematical notation for the length of a
vector. The equation is the same for any dimension of vector: square the mem-
bers, add them together, and take the square root.
This formula is simple to translate into code. It is broken into two functions: one
function will square and add the members;
the other will perform the
square root.
public double Length()
{
return Math.Sqrt(LengthSquared());
}
 
Search WWH ::




Custom Search