Point Inside of a Triangle Detection

Here is the ActionScript 3 code I used to detect if the player's ship is inside of a triangle formed by three of the green enemy ships in the Flash game Triangulation:

private function dot(vect1:Array, vect2:Array) : Number
{
  return(vect1[0]*vect2[0] + vect1[1]*vect2[1]);
}

private function inTriangle(t1:Array, t2:Array, t3:Array, point:Array) : Boolean
{
  var invDenom:Number = new Number;
  var u:Number = new Number;
  var v:Number = new Number;
  var dot00:Number = new Number;
  var dot01:Number = new Number;
  var dot02:Number = new Number;
  var dot11:Number = new Number;
  var dot12:Number = new Number;
  var v0:Array = new Array(2);
  var v1:Array = new Array(2);
  var v2:Array = new Array(2);

  // Compute vectors
  v0[0] = t3[0] - t1[0];
  v1[0] = t2[0] - t1[0];
  v2[0] = point[0] - t1[0];
  v0[1] = t3[1] - t1[1];
  v1[1] = t2[1] - t1[1];
  v2[1] = point[1] - t1[1];

  // Compute dot products
  dot00 = dot(v0, v0);
  dot01 = dot(v0, v1);
  dot02 = dot(v0, v2);
  dot11 = dot(v1, v1);
  dot12 = dot(v1, v2);

  // Compute barycentric coordinates
  invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
  u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  v = (dot00 * dot12 - dot01 * dot02) * invDenom;

  // Check if point is in triangle
  return (u > 0) && (v > 0) && (u + v < 1);
}

I got this method from blackpawn's blog. Check out his explanation and cool Flash demonstration.

  1. December 28th, 2009 at 12:59 | #1

    Leave me a comment on this method of detecting whether a point is inside of a triangle.

  2. Digao
    October 12th, 2011 at 12:33 | #2

    Fantastic. It was very usefull for me. Thanks.

  3. Liz
    September 13th, 2013 at 11:17 | #3

    Oh my gosh. Thank you SO much. I needed something like this for a Geolocation API. I had tried a variety of solutions, all of which were over complicated, didn’t show enough of the tutorial, I couldn’t find anything that worked! Until I found this from you. THANK YOU, thank you thank you! You’re the best! :D