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;
}

Math - Calculate a normal vector from three position vectors

This Vector3 constructor calculates a surface normal from three 3D vectors.
public Vector3(Vector3 a, Vector3 b, Vector3 c) {
  var u = b - a; //Requires an overloaded minus
  var v = c - a; //operator for two vector3's.
  X = (u.Y * v.Z) - (u.Z * v.Y);
  Y = (u.Z * v.X) - (u.X * v.Z);
  Z = (u.X * v.Y) - (u.Y * v.X);
  Normalize();
}