Find if a point is within a triangle: Difference between revisions
Content added Content deleted
Alextretyak (talk | contribs) |
(add FreeBASIC) |
||
Line 669: | Line 669: | ||
.................... |
.................... |
||
.................... |
.................... |
||
</pre> |
|||
=={{header|FreeBASIC}}== |
|||
<lang freebasic> |
|||
type p2d |
|||
x as double 'define a two-dimensional point |
|||
y as double |
|||
end type |
|||
function in_tri( A as p2d, B as p2d, C as p2d, P as p2d ) as boolean |
|||
'uses barycentric coordinates to determine if point P is inside |
|||
'the triangle defined by points A, B, C |
|||
dim as double AreaD = (-B.y*C.x + A.y*(-B.x + C.x) + A.x*(B.y - C.y) + B.x*C.y) |
|||
dim as double s = (A.y*C.x - A.x*C.y + (C.y - A.y)*P.x + (A.x - C.x)*P.y)/AreaD |
|||
dim as double t = (A.x*B.y - A.y*B.x + (A.y - B.y)*P.x + (B.x - A.x)*P.y)/AreaD |
|||
if s<=0 then return false |
|||
if t<=0 then return false |
|||
if s+t>=1 then return false |
|||
return true |
|||
end function |
|||
dim as p2d A,B,C,P 'generate some arbitrary triangle |
|||
A.x = 4.14 : A.y = -1.12 |
|||
B.x = 8.1 : B.y =-4.9 |
|||
C.x = 1.5: C.y = -9.3 |
|||
for y as double = -0.25 to -9.75 step -0.5 'display a 10x10 square |
|||
for x as double = 0.125 to 9.875 step 0.25 |
|||
P.x = x : P.y = y |
|||
if in_tri(A,B,C,P) then print "@"; else print "."; 'with all the points inside the triangle indicated |
|||
next x |
|||
print |
|||
next y |
|||
</lang> |
|||
{{out}}<pre>........................................ |
|||
........................................ |
|||
................@....................... |
|||
................@@@..................... |
|||
...............@@@@@@................... |
|||
..............@@@@@@@@@................. |
|||
..............@@@@@@@@@@@............... |
|||
.............@@@@@@@@@@@@@@@............ |
|||
.............@@@@@@@@@@@@@@@@@.......... |
|||
............@@@@@@@@@@@@@@@@@@@@........ |
|||
...........@@@@@@@@@@@@@@@@@@@.......... |
|||
...........@@@@@@@@@@@@@@@@............. |
|||
..........@@@@@@@@@@@@@@................ |
|||
.........@@@@@@@@@@@@................... |
|||
.........@@@@@@@@@...................... |
|||
........@@@@@@@......................... |
|||
.......@@@@@............................ |
|||
.......@@............................... |
|||
........................................ |
|||
........................................ |
|||
</pre> |
</pre> |
||