0

I would like to find a way to know if I click on a line. I have a standard 2D plan with square for example and a line between both. I would like to detect when I click on the line. The line can be horizontal, vertical or with an angle. I have those information on the line :

-Starting coordinate (x,y)

-Ending coordinate (x,y)

-The mouse click position (x,y)

I might be able to get the angle with tan(). I found this solution but i can't add mouse event: How to select a line

Thanks you.

Community
  • 1
  • 1

2 Answers2

0

Have a look at this answer:

Shortest distance between a point and a line segment

They calculate the shortest distance from a point to a segment.

Having calculated this value, you can accept or reject the mouse click event:

if ( distanceToSegment(...) < threshold && mouseClicked()) {
     // insert code here
}

The threshold will depend on how precise you want the user to be.

Community
  • 1
  • 1
Juan Leni
  • 6,982
  • 5
  • 55
  • 87
  • If I take the end point of my line and the mousepoint and it's the same angle as the line, does it means im clicking on the line ? – ILoveWaffle Nov 24 '14 at 19:02
  • I think it is important to differentiate between a line and a segment. What you are saying is correct for a line but not for a segment. You could be clicking outside the segment. You would need to check that the point is also in the same X interval – Juan Leni Nov 24 '14 at 19:06
  • 1
    Now also keep in mind that resolution can be very high, you want to give the user some margin for error. That's the reason that calculating the distance can be handy and will result in a much more reliable approach. – Juan Leni Nov 24 '14 at 19:08
0

Let S and E be the segment endpoints and M the mouse.

The vector that joins M to a point along SE is given by MS+t.SE, where 0<t<1.

Square this vector to get its (squared) length: d²=SE²t²+2(SE.MS)t+MS²,

and find the position of the minimum, t=-(SE.MS)/SE².

If t<=0, the shortest distance is to S, hence d²=MS².

If t>=1, the shortest distance is to E, hence d²=ME².

Else, the shortest distance is to a point on the segment, and d²=MS²-(SE.MS)²/SE².

There is no need to take the square root, because d<Tolerance is equivalent to d²<Tolerance².

  • I did something like that. Let's take x,y,x1,y2,x2,y2 - M.X, M.Y, S.X, S.Y., E.X, E.Y. (x - x1) / (x2 - x1) = (y - y1) / (y2 - y1) tell me if I click on the line. How can I had tolerance to this ? It's very interesting. – ILoveWaffle Nov 25 '14 at 01:53
  • Comparing the slopes has two drawbacks: 1. it works for infinite lines, not for line segments, 2. the allowance gets larger and larger as you step away from P1. –  Nov 25 '14 at 07:38