is mouse on line?

Blitz3D Forums/Blitz3D Beginners Area/is mouse on line?

jhocking(Posted 2004) [#1]
How do you determine if the mouse cursor is on a line? My situation is that I have two points, defined by coordinates x1,y1 and x2,y2. When I click the mouse I want to know if I clicked on the line connecting those two points.


Ross C(Posted 2004) [#2]
Hey, ok, how about this. First off find the gradient of the line. now, find the gradient of the first point of the line to the mouse (x,y). Now compare these. If they are the same, then the point lies on a straight line.

You first need to check the x co-ord of the mouse is between the two x co-ords and the two y co-ords of the line.


Bot Builder(Posted 2004) [#3]
just as a note, the 'gradient' is often known as the slope of the line. also, you need to check for vertical lines(no x change) befrore computing the slope, as it is a division by zero. You can then say that the mouse is on the lne if both lines are vertical.


jhocking(Posted 2004) [#4]
Thanks guys, works great.


Beaker(Posted 2004) [#5]
Here is an alternative:

If the distances of the mouse to each point added together is almost equal to the distance of one point to another then the mouse is on the line. Pseudo code:

If Abs((Dist2D(mousex,mousey,p1x,p1y)+Dist2D(mousex,mousey,p2x,p2y))-Dist2D(p1x,p1y,p2x,p2y)) < line_thickness#
;mouse is on line
EndIf

This also works in 3D.


jhocking(Posted 2004) [#6]
Clever. I'll have to benchmark to see which method is faster. Since I'll be doing this check hundreds of times in a loop every frame it's probably speed critical.

ADDITION: Actually, the distance way works better because it has an easily controlled threshold value (line_thickness.) With the slopes method I was needing to click exactly on the line. I thought of a way to do a threshold but that would have been a pain and probably pretty slow.


Bot Builder(Posted 2004) [#7]
mmm. yes, very clever. will remember that one.