5
\$\begingroup\$

When the mouse button is clicked, I want to draw a line from (0, random) to (640, y) which goes through the click position.

example

How would I calculate the y coordinate of the end of the line?

\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

You have a Point with the origin, and a Point with the mouse position. Let's find the unitary directional vector:

Vector2 direction;
direction.X = mouse.X - origin.X;
direction.Y = mouse.Y - origin.Y;
Normalize(direction);

This way you'll get a vector that points from the origin to the mouse coords, and whose components satisfy the Pythagorean theorem. Now you only have to find the distance the line travels from the origin point until the X component is 640:

Point endPoint;
float distance = 640.0 / direction.X;
endPoint.X = origin.X + (direction.X * distance);
endPoint.Y = origin.Y + (direction.Y * distance);
\$\endgroup\$
1
\$\begingroup\$

The equation of a line through two known points is y − y1 = [(y2 − y1) / (x2 − x1)] · (x − x1). Substitute (x1, y1) = (0, random), x = 640, and then solve for y in terms of (x2, y2), which is your mouse's location.

When implementing it, you'd need to check for division by zero, in case the mouse position happened to be on the line x = 0.

\$\endgroup\$

You must log in to answer this question.