2
\$\begingroup\$

I know the vectors that describe two perpendicular lines, $$\mathbf{a} + \lambda\mathbf{d}$$ and $$\mathbf{b} + \mu\mathbf{d'}$$ I've written a JavaScript function to get the coordinates of the point of intersection of two such lines. It is guaranteed that they will intersect, since in my case the lines are perpendicular. (Perhaps I could reduce the number of arguments by 1 since d' is just a perpendicular direction vector to d?)

I solved the system of equations via substitution

$$ \left(\begin{array}{r}\mathbf{a}_x\\\mathbf{a}_y\end{array}\right) + \lambda\left(\begin{array}{r}\mathbf{d}_x\\\mathbf{d}_y\end{array}\right) = \left(\begin{array}{r}\mathbf{b}_x\\\mathbf{b}_y\end{array}\right) + \mu\left(\begin{array}{r}\mathbf{d'}_x\\\mathbf{d'}_y\end{array}\right) $$

$$ \lambda = \frac{\mathbf{b}_x+\mu\mathbf{d'}_x-\mathbf{a}_x}{\mathbf{d'}_x} $$

$$ \mu = \frac{\mathbf{a}_y\mathbf{d}_x+\mathbf{b}_x\mathbf{d}_y-\mathbf{a}_x\mathbf{d}_y-\mathbf{b}_y\mathbf{d}_x}{\mathbf{d'}_y\mathbf{d}_x-\mathbf{d}_y\mathbf{d'}_x} $$

And directly implemented this in JavaScript.

The function I've written looks like:

function getIntersection(a, d, b, d_) {
  const [ax, ay] = a;
  const [dx, dy] = d;
  const [bx, by] = b;
  const [d_x, d_y] = d_;
  const µ = (ay*dx + bx*dy - ax*dy - by*dx) / (d_y*dx - dy*d_x);
  return [bx + µ*d_x, by + µ*d_y];
}

How can I improve this function?

Especially worried about:

  • making it easier to read/maintain
  • better algorithms for solving the problem
\$\endgroup\$
1
  • \$\begingroup\$ Just make sure your code does not lie ;) If your function only solves for perpendicular lines then that should be reflected in the function name or there should at least be a comment stating that. \$\endgroup\$
    – konijn
    Nov 16, 2021 at 8:27

1 Answer 1

1
\$\begingroup\$

If the lines are truly perpendicular then you don't need d_ since it is either [dy, -dx] or [-dy, dx].

If I choose the first one and replace d_x by -dy and d_y by dx and substitube this into your function I get:

function getIntersection(a, d, b) {
  const [ax, ay] = a;
  const [dx, dy] = d;
  const [bx, by] = b;
  const µ = (ay*dx + bx*dy - ax*dy - by*dx) / (dx*dx + dy*dy);
  return [bx - µ*dy, by + µ*dx];
}

Which is slightly shorter and less redundant. One final step I can see is:

function getIntersection(a, d, b) {
  const [ax, ay] = a;
  const [dx, dy] = d;
  const [bx, by] = b;
  const µ = (dx*(ay - by) + dy*(bx - ax)) / (dx*dx + dy*dy);
  return [bx - µ*dy, by + µ*dx];
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ @theonlygusti I agree with the comment of "konijn" on your question. Perhaps the function should be renamed to getProjection() or getPointProjectionOntoLine(). \$\endgroup\$ Nov 16, 2021 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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