I have been working on this problem for a while now and can’t figure out the solution. Hence my post on this forum. I’m trying to figure out the position of a symbol on a line. These lines are located in a grid with XY coordinates. Based on the position of the mouse, I want to determine the XY coordinates of the symbol on the nearest line.

In principle, the XY coordinates for each element known.

  • The two XY coordinates of each line from point A to point B 
  • The XY coordinates of the mouse position

I want to do this walking through the following steps:

Step 1: Calculate Nearest line by determining height line to each line.

enter image description here

$$ cos(\alpha) = \frac{b^{2} + c^{2} - a^{2}}{2bc} $$

$$ A = cos^{-1}\alpha $$

$$ h = (sin(\alpha))(b) $$

By calculating the height of each line to the mouse position, I can select the nearest line where the symbol should be positioned.

Step 2: Determine the position of symbol on the line:

This is the step where having issues. First I want to explain accompanying drawing.

  • The red triangle are three separate lines with a known XY at point A and point B.
  • The orange line is the calculated height from step 1.
  • The blue Lines are guidelines to determine the height of the line as in Step 1.
  • The gray circles are the potential mouse positions.


The question now is, how do I calculate the XY coordinates of the point where the height line meets on the red line. Regardless of the mouse position (top, bottom, left or right of the red line). So, when using tan, sin or cos is the opposite or oblique side is not always the intended line.


Let me give it a try. If I understood everything correctly, you have a triangle $ABC$ with known coordinates of $A = (a_1, a_2), B = (b_1, b_2)$ and $C = (c_1, c_2)$.

You also have a mouse position $M = (m_1, m_2)$.

You already found out which line is nearest. Wlog I can assume this is the line $AB$.

The points $(x_1, x_2)$ on the line through $AB$ are described by $$(x_1, x_2) = \lambda (b_1 - a_1, b_2 - a_2) + (a_1, a_2)$$

The line going through the mouse position and perpendicular to the line through $AB$ is given by $$(x_1, x_2) = \mu (a_2 - b_2, b_1 - a_1) + (m_1, m_2)$$

The intersection of both lines is the point you're looking for. In order to find it, you'll have to find either $\lambda$ or $\mu$ from $$ \mu (a_2 - b_1) + m_1 = \lambda (b_1 - a_1) + a_1 $$ and $$ \mu (b_1 - a_1) + m_2 = \lambda (b_2 - a_2) + a_2 $$ I leave that as an exercise ;-)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.