As you may be able to tell from this screenshot, I am trying to make a physics engine for a platformer I am working on, but I have run into a definite problem: I need to be able
If you take the cross product of the two vectors:
p1 - p0
and
p2 - p0
where p0
, p1
and p2
are three vertices of the triangle, you'll get the normal. A triangle is considered to be pointing towards you if the vertices are ordered clockwise with respect to its outward normal. This is called the left hand rule. Imagine holding your left hand with your fingers curled from p0
to p1
, your thumb sticks out in the direction of the face normal:
To finish answering your question, once you have the unit normal vector of your triangle you can work out the angle using a dot product.
The dot product of two unit vectors is equal to the cosine of the angle between them, so if you calculate the arccos of the dot product of your unit normal vector and your unit Up vector you will get the slope angle of your triangle (angle away from horizontal).
Also, note that OpenGL conventionally uses a right-handed coordinate system, so if you are using that then your triangle vertices will have a counter-clockwise ordering.
There are 2 normals to the triangle (of course) and the one you get from standard algorithms depends on the order of ther vertices. Quoting wiki
"For a polygon (such as a triangle), a surface normal can be calculated as the vector cross product of two (non-parallel) edges of the polygon."
But the direction of the normal depends on the order of points chosen, you can calculate it and decide using some other heuristics whether the reverse vector is the normal you are interested in.
The cross product is the right answer. Dont forget to normalise the result, and dont forget that if the triangle has zero area, the result is invalid because there is no well defined normal. Basically, if your three vertices are p0, p1 and p2:
vector temp = cross(p1 - p0, p2 - p0);
if (length(temp) < epsilon) then
Degenerate_triangle_error;
else
return normalize(temp);
Also, as the other answer says, whether you get the 'up facing' or 'down facing' normal will depend on the ordering of your vertices.