# Area of a Triangle, this code seems to work, why?

I had this formula in some really really old code of mine. It calculates the area inside a triangle. I looked around the web and everything was far more compilcated than this. In my sample testing this appears to work. Someone smarter than me, does it work? Does it only work in special cases?

``````for(int ii = 0 ; ii < indices.Length; ii+=3)
{
Vector2 A = Points[indices[ii]];
Vector2 B = Points[indices[ii+1]];
Vector2 C = Points[indices[ii+2]];
Area += Mathf.Abs((A.x - C.x) * (B.y - A.y) - (A.x - B.x) * (C.y - A.y)) * 0.5f;
}
``````

Exactly, the formula in your question only works for right angled triangles.

The cross product of two vectors gives you a vector which length is equal to the area of the parallelogram made up by the two vectors. Just take the half of it and you get the area of the triangle:

``````//C#
// I guess Points are Vector3 values? Well it doesn't really matter
// but the cross product is only defined for R3

for(int ii = 0 ; ii < indices.Length; ii+=3)
{
Vector3 A = Points[indices[ii]];
Vector3 B = Points[indices[ii+1]];
Vector3 C = Points[indices[ii+2]];
Vector3 V = Vector3.Cross(A-B, A-C);
Area += V.magnitude * 0.5f;
}
``````

edit
If you really work with Vector2 (so all your triangles are int the x-y-plane) you can optimise it be changing this line:

``````Area += V.magnitude * 0.5f;
``````

to:

``````Area += Mathf.Abs(V.z) * 0.5f;
``````

This will drop the need for a square-root which is the slowest part of the whole calculations here.

It only works accurately for right angled triangles I would imagine as it appears to be using 1/2 of the squares - not totally convinced it’s right then - but unlikely that it is right for anything without a right angle.