TRIANGLE/POINT
To test if a point is inside a triangle, we compare the area of the original triangle with the sum of the area of three triangles made between the point and the corners of the triangle.
Here's a diagram demonstrating the triangles created for a point outside and inside the triangle:
To get the area, we use Heron's Forumula:
var areaOrig = ;
We need to calculate the area of the three triangles made from the point as well:
var area1 = ;var area2 = ;var area3 = ;
If we add the three areas together and they equal the original, we know we're inside the triangle! Using this, we can test for collision:
if area1 + area2 + area3 == areaOrig return true;return false;
Here's a full example:
var px = 0; // point (set by mouse)var py = 0; var x1 = 300; // three points of the trianglevar y1 = 100;var x2 = 450;var y2 = 300;var x3 = 150;var y3 = 300; { var canvas = ; canvasparent"sketch"; ; ; // make point easier to see} { ; // mouse point to mouse coordinates px = mouseX; py = mouseY; // check for collision // if hit, change fill color var hit = ; if hit ; else ; ; ; // draw the point ; ;} // TRIANGLE/POINT { // get the area of the triangle var areaOrig = ; // get the area of 3 triangles made between the point // and the corners of the triangle var area1 = ; var area2 = ; var area3 = ; // if the sum of the three areas equals the original, // we're inside the triangle! // (< 1 due to floating point issues in Javascript) if Math < 1 return true; return false;}
This example was built on a modified version of a post on YoYo Games. If you would like to read a lengthy discussion on the merits and problems with this method, and many other suggestions, see this thread on GameDev.net.