# Drawing a line from a random coordinate through a given point

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

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

-

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);
-

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.

-