Hello everyone.
We were learning at school about transformations on an axis, and I got this idea to combine it with finding whether a point is in a triangle or not.
The function:
function SB_GetInTriangle(x1#, y1#, x2#, y2#, x3#, y3#, x#, y#)
`Initialize some variables
dec x2#, x1# : dec y2#, y1#
dec x3#, x1# : dec y3#, y1#
dec x#, x1# : dec y#, y1#
`Get L
L# = ((x2# * y#) - (x# * y2#)) / ((x2# * y3#) - (y2# * x3#));
`Exlude 0
if L# < 0 then exitfunction 0
`Get newX
newX# = (x# - (x3# * L#)) / x2#
if newX# < 0.0 then exitfunction 0
`Final check
if newX# > 1 - L# then exitfunction 0
`Point is in triangle
endfunction 1
I know this is bound to die. But I'm posting this for anyone trying to search the forum.
I also did some speed tests, and this method is surprisingly one of the fastest methods.
Attached is a dll with one poor function, namely the one I just gave in DBP code. Include it in
Compiler>plugins-user to make it work.
The syntax of the command is:
GetInTriangle(float x1, float y1, float x2, float y2, float x3, float y3, float x, float y)
returns:
1 if (
x,
y) is in triangle,
0 if not.
The DLL is overall much faster (1000000 times in 303 ms according to my tests on this computer).
And finally an example:
sync on : sync rate 0
x1# = 100
y1# = 100
x2# = 500
y2# = 500
x3# = 600
y3# = 100
do
cls
a = SB_GetInTriangle(x1#, y1#, x2#, y2#, x3#, y3#, mousex(), mousey())
if a = 1 then print "Mouse is in triangle" else print "Mouse is not in triangle"
`Display triangle
line x1#, y1#, x2#, y2#
line x2#, y2#, x3#, y3#
line x1#, y1#, x3#, y3#
sync
loop
function SB_GetInTriangle(x1#, y1#, x2#, y2#, x3#, y3#, x#, y#)
`Initialize some variables
dec x2#, x1# : dec y2#, y1#
dec x3#, x1# : dec y3#, y1#
dec x#, x1# : dec y#, y1#
`Get L
L# = ((x2# * y#) - (x# * y2#)) / ((x2# * y3#) - (y2# * x3#));
`Exlude 0
if L# < 0 then exitfunction 0
`Get newX
newX# = (x# - (x3# * L#)) / x2#
if newX# < 0.0 then exitfunction 0
`Final check
if newX# > 1 - L# then exitfunction 0
`Point is in triangle
endfunction 1
It's the programmer's life:
Have a problem, solve the problem, and have a new problem to solve.