You definitely need to use floats, even if the dot and line coordinates are integers the math involved requires floats.
Given point P and line segment AB:
rem make a random line
ax = rnd(640) : ay = rnd(480)
bx = rnd(640) : by = rnd(480)
hide mouse
do
cls
rem mouse position
mx = mousex()
my = mousey()
rem draw a new random line
if spacekey()
ax = rnd(640)
ay = rnd(480)
bx = rnd(640)
by = rnd(480)
endif
rem if point is within 10 pixels of the line, make it green.
rem remember this function returns the squared distance, so
rem if comparing within 10 units, square it first to equal 100.
if DistanceFromLine(ax, ay, bx, by, mx, my, 10) <= 100
ink rgb(0, 255, 0), 0
else
ink rgb(255,0,0), 0
endif
rem draw the line
line ax, ay, bx, by
rem show mouse's position
ink rgb(255,255,255), 0
circle mx, my, 2
loop
function DistanceFromLine(ax, ay, bx, by, px, py, distance)
x = bx - ax
y = by - ay
n = (px - ax)*x + (py-ay)*y
d# = x^2 + y^2
u# = n / d#
rem These two lines are required if checking
rem a line segment. If checking an infinite
rem line, then remove them.
if u# > 1 then u# = 1
if u# < 0 then u# = 0
rem point of intersection
ix = ax + (bx-ax)*u#
iy = ay + (by-ay)*u#
rem this is the squared distance of the point from the line
rem if you need the actual distance, use sqrt around it,
rem otherwise this is faster when 'comparing' distances.
d2# = (px - ix)^2 + (py - iy)^2
endfunction d2#
Other useful equations can be found on my website:
http://dbcodecorner.com/?page=eq
Oh, and easiest way for finding the normal of a line (this still requires normalization if needed as a unit vector), then for line AB:
N.x = B.y - A.y
N.y = -(B.x - A.x)