0

I know this should be pretty simple, but I can't figure out the following: I want to write a function that checks if two one-dimensional lines intersect. if they intersect return "true", else return "false".

I have two lines named A and B. Each line has two endpoints (A1, A2 / B1, B2). My logic is that if the two lines intersect "A2 >= B1 && B2 >= A1" is true. However, that doesn't seem to work.

function linesIntersect (A1, A2, B1, B2) {
  if (A2 >= B1 && B2 >= A1) {
  return true
  } else {
  return false
  }
}

Any help is welcome. Thanks!

  • 2
    Possible duplicate of [Test if two lines intersect - JavaScript function](http://stackoverflow.com/questions/9043805/test-if-two-lines-intersect-javascript-function) – display name Oct 16 '16 at 15:57

1 Answers1

2

The lines intersect if either: a) The first line starts before the second and ends after the second one starts. b) The other way around. So:

function overlap(A1,A2,B1,B2) {
    return (A1<=B1 && A2>=B1) || (B1<=A1 && B2>=A1);
}

Or:

function overlap(A1,A2,B1,B2) {
    return A1<=B1?A2>=B1:B2>=A1;
}
unholybear
  • 191
  • 6
  • Thanks for your answer. The return should be "false" or "true", though. So, the question is: how can I check if (A1<=B1 && A2>=B1) || (B1<=A1 && B2>=A1) is true (lines overlap)? –  Oct 16 '16 at 20:10
  • (A1<=B1 && A2>=B1) || (B1<=A1 && B2>=A1) is a boolean expression, i.e. exactly what you need, false or true, depending on your parameters. – unholybear Oct 17 '16 at 06:29
  • so the full function will be: `function overlap(A1,A2,B1,B2){ return A1<=B1?A2>=B1:B2>=A1;}` – unholybear Oct 17 '16 at 06:32