Find if a point is within a triangle.



Task

   Assume points are on a plane defined by (x, y) real number coordinates.
   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. 
   You may use any algorithm. 
   Bonus: explain why the algorithm you chose works.


Related tasks

   Determine_if_two_triangles_overlap


Also see

 Discussion of several methods. [[1]]
 Determine if a point is in a polygon [[2]]
 Triangle based coordinate systems [[3]]
 Wolfram entry [[4]]


10 PIT1X! = 3 : PIT1Y! = 1.3 :    REM arbitrary triangle for demonstration
20 PIT2X! = 17.222 : PIT2Y! = 10
30 PIT3X! =  5.5 : PIT3Y! = 18.212
40 FOR PITPY! = 0 TO 19 STEP 1
50 FOR PITPX! = 0 TO 20 STEP .5
60 GOSUB 1000
70 IF PITRES% = 0 THEN PRINT "."; ELSE PRINT "#";
80 NEXT PITPX!
90 PRINT
100 NEXT PITPY!
110 END
1000 REM Detect if point is in triangle. Takes 8 double-precision
1010 REM values: (PIT1X!, PIT1Y!), (PIT2X!, PIT2Y!), (PIT3X!, PIT3Y!)
1020 REM for the coordinates of the corners of the triangle
1030 REM and (PITPX!, PITPY!) for the coordinates of the test point
1040 REM Returns PITRES%: 1=in triangle, 0=not in it
1050 PITDAR! = -PIT2Y!*PIT3X! + PIT1Y!*(-PIT2X! + PIT3X!) + PIT1X!*(PIT2Y - PIT3Y!) + PIT2X!*PIT3Y!
1060 PITXXS = (PIT1Y!*PIT3X! - PIT1X!*PIT3Y! + (PIT3Y! - PIT1Y!)*PITPX! + (PIT1X! - PIT3X!)*PITPY!)/PITDAR!
1070 PITXXT = (PIT1X!*PIT2Y! - PIT1Y!*PIT2X! + (PIT1Y! - PIT2Y!)*PITPX! + (PIT2X! - PIT1X!)*PITPY!)/PITDAR!
1080 PITRES% = 0
1090 IF PITXXS!<=0 THEN RETURN
1100 IF PITXXT!<=0 THEN RETURN
1110 IF PITXXS!+PITXXT!>=1 THEN RETURN
1120 PITRES% = 1
1130 RETURN