1

I have game object that moves along a path on a 2D plane, between 2 points (x1,y1) and (x2,y2). Occasionally it gets moved off the path and needs to be put back on it. When this happens I'll know the x-coordinate, but need to calculate the y-coordinate along the path given the x-coordinate.

Here's an illustration of what I mean:

example here

Rodrigo de Azevedo
  • 1,097
  • 9
  • 17
Rich
  • 29
  • 3

2 Answers2

3

You have a line segment, i.e., the set of all convex combinations of the given endpoints. You would like to find the coefficients that yield the convex combination (x3,y3), where y3 is unknown.

t (x1,y1) + (1-t) (x2,y2) = (x3,y3)

Since x3 is known, we obtain

t = (x3 - x2) / (x1 - x2)

and, thus,

y3 = ((x3-x2) y1 + (x1-x3) y2) / (x1 - x2)
Rodrigo de Azevedo
  • 1,097
  • 9
  • 17
0

The general equation of a line in 2D is a.x + b.y + c = 0 where the vector U = (-b, a) is a direction vector of the line.

Because (x1, y1) and (x2, y2) are on the line, you know that:

  • a.x1 + b.y1 + c = 0
  • a.x2 + b.y2 + c = 0
  • (x2-x1, y2-y1) is a direction vector of the line so: -b = x2-x1 and a = y2-y1

So one equation of your line ax + by + c = 0 with :

  • a = y2-y1
  • b = x1-x2
  • c = -a.x1 - b.y1 = x1(y1-y2) + y1(x2-x1)

Knowing a, b, c and x3, you can easily find y3:

  • y3 = -(c + a.x3) / b

Pay attention nevertheless to the case where b = 0 (case of a vertical line)

Pierre Baret
  • 1,773
  • 2
  • 17
  • 35