I'm working on a paint-like program in C#. I want to be able to erase a line when clicking close to it (distance < 10 pixels for example). I have tried different calculations and the problem I continuously end up having is that the line will only be erased when I click near either the starting point of the line or the end point. Anything in between definitely does not seem to work.
Let p be the point the user had clicked on in the form, startp and endp the end points of the line.
double a = (endp.Y - startp.Y) / (endp.X - startp.X); // gradient
double b = endp.Y - a * endp.X; // y intercept
// condition such that it only works when i click close to the line segment,
// not the entire infinite line for which the calculation y=ax+b works
double yvalue = p.X * a + b; // value the line segment has at the x-value which the user clicks on
double alpha = Math.Atan((endp.X - startp.X) / (endp.Y - startp.Y));
double distance = Math.Sin(alpha) * Math.Abs((yvalue - p.Y));
if (distance<10)
// remove line
Why does this code only work for points close to the start or end points? I'm confident that it is not because of the conditions I use which I have left out of my example here