In the following examples all the images will show a four point object. This is just because my code uses mostly four point polygons and the points are parallel to each other. To make sure the normal is calculated properly it is best to use only triangles or quads that you know that exist in a plane. First we get two vectors from the triangle, this is done by taking one of the points and subtracting it from the other two (where x, y, z are properly subtracted):
vector1 = point2 - point1 vector2 = point3 - point1
We then do the cross product on the two vectors and come up with only one vector. The calculation for this is done as follows:
vector3.x = (vector1.y * vector2.z) - (vector1.z * vector2.y); vector3.y = (vector1.z * vector2.x) - (vector1.x * vector2.z); vector3.z = (vector1.x * vector2.y) - (vector1.y * vector2.x);
Now the only thing left to do is make sure the length is one, which is called normalizing. We first get the current length of the vector and then divide each axis by the length:
length = sqrt((vector3.x)² + (vector3.y)² + (vector3.z)²);
normal.x = vector3.x / length; normal.y = vector3.y / length; normal.z = vector3.z / length;
|