I have an arrow drawn between two objects on a Winform.
What would be the simplest way to determine that my mouse is currently hovering over, or near, this line.
I have considered testing whether the mouse point intersects a square defined and extrapolated by the two points, however this would only be feasible if the two points had very similar x or y values.
I am thinking, also, this problem is probably more in the realms of linear algebra rather than simple trigonometry, and whilst I do remember the simpler aspects of matrices, this problem is beyond my knowledge of linear algebra.
On the other hand, if a .NET library can cope with the function, even better.
EDIT Thanks for the answers, there were a few very good ones all deserving being tagged as answered.
I chose Coincoin's answer as accepted, as I like that it could be applied to any shape drawn, however ended up implementing Tim Robinson's equation, as it appeared much more efficient to with a simple equation rather than newing up graphics paths and pens, as in my case I need to do it onMouseMove for 1-n different relationships (obviously there would be some caching and optimisations, but the point still remains)
The main issue with the equation was that it appeared to treat the line as infinite, so I added a bounds test as well.
The code (initial cut, I'll probably neaten it a bit), for those interested, is below
if (Math.Sqrt( Math.Pow(_end.X - _start.X, 2) +
Math.Pow(_end.Y - _start.Y, 2) ) == 0)
{
_isHovering =
new RectangleF(e.X, e.Y, 1, 1).IntersectsWith(_bounds);
}
else
{
float threshold = 10.0f;
float distance = (float)Math.Abs(
( ( (_end.X - _start.X) * (_start.Y - e.Y) ) -
( (_start.X - e.X) * (_end.Y - _start.Y) ) ) /
Math.Sqrt( Math.Pow(_end.X - _start.X, 2) +
Math.Pow(_end.Y - _start.Y, 2) ));
_isHovering = (
distance <= threshold &&
new RectangleF(e.X, e.Y, 1, 1).IntersectsWith(_bounds)
);
}
and _bounds is defined as:
_bounds = new Rectangle(
Math.Min(_start.X, _end.X),
Math.Min(_start.Y, _end.Y),
Math.Abs(_start.X - _end.X), Math.Abs(_start.Y - _end.Y));