02 March 2021

Math - Normalize a 3D vector

This method is part of the Vector3 class, and changes the vector into a unit vector.
void Normalize() {
  if (IsZero) return; //X, Y and Z are 0: it would set each component to NaN.
  float length = (float)Math.Sqrt(X * X + Y * Y + Z * Z);
  X /= length;
  Y /= length;
  Z /= length;
}

No comments:

Post a Comment