Game Development Reference
In-Depth Information
public double LengthSquared()
{
return (X * X þ Y*Y þ Z * Z);
}
If you want to compare the length of two vectors the LengthSquared opera-
tion can be compared instead of the Length , saving a square root operation and
making it slightly more efficient.
Vector Equality
Vectors are considered equal if all the members' values, X,Y, and Z, are equal.
Vectors don't have a position; they are just a direction from some origin.
Figure 8.3 has a number of vectors; even though some vectors are placed at
different positions, they are still equal because all their members are equal. Three
miles north is still three miles north if it's three miles north of your house, or
three miles north of the Great Pyramid of Giza.
It is simple to create an Equals function for the vector.
public bool Equals(Vector v)
{
return (X == v.X) && (Y == v.Y) && (Z == v.Z);
}
In code it would be convenient if the == operator was also overloaded. At the
moment, the following cannot be written
// Cannot write this
if (vector1 == vector2)
{
System.Console.WriteLine("They're the same")
}
// Instead must write
if (vector1.Equals(vector2))
{
System.Console.WriteLine("They're the same")
}
To use the == operator, it needs to be overloaded and that requires a few
more functions to be overridden as well, GetHashCode , != , and Equals
(Object obj) .
 
Search WWH ::




Custom Search