Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

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);
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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