Question

I just recognized my math is a bit rusty.. I wanna check if Point C is between Point A and Point B. C can be on the line segment of A and B, or not. There can be three cases and I have to identify all of them:

  • C is between A and B

       C  
      / \  
     A---B
    
  • C is in front of A and B

    C  
     \  \
      A--B
    
  • C is in the back of A and B

           C  
       /  /
      A--B 
    

The "sketch" in the last two points should be a triangle.

I used the dotproduct to check if C is between A and B.

if (VectorOf(AB) * VectorOf(BC)) >= 0)

To check if C is in the back of A and B i use this:

if (VectorOf(AB) * VectorOf(BC)) < 0)

But how to identify if C is in front of A and B?

Was it helpful?

Solution

Just use the dot product starting from point B.

if (VectorOf(AC) * VectorOf(AB) < 0) {
    // C is on the left of A
}
else {
    if (VectorOf(BC) * VectorOf(BA) < 0) {
        // C is on the right of B
    }
    else {
        // C is between A and B
    }
}

Alternatively, you can compute the projected distance, relative to vector AB :

(VectorOf(AC) * VectorOf(AB)) / (VectorOf(AB) * VectorOf(AB))

The result would be < 0, between 0 and 1, or > 1 in your three cases, as shows the math below :

      C
     /│
    / │
   /  │
──A── H ─────B─────

The definition of the dot product is that

AC · AB = AC×AB×cos(Â) = AH×AB (signed : negative if C is left of A, positive if C is to the right).

AB · AB = AB² (positive)

The result of the division is the signed ratio AH/AB :

-   0          1   >1
────A── H ─────B─────

OTHER TIPS

How about using coordinates:

Between: a.x > c.x > b.x || a.x < c.x < b.x
Front: c.x < a.x && b.x
Back: c.x > b.x && a.x

I'm assuming that A,B don't necessarily have the same Y coordinate, even though this is what the diagrams would suggest. You would want to use vector projection.

let b = B - A, c = C - A, then the projection is: u = dot(b,c) / |b|,

Front: u < 0; Between: 0 <= u <= |b|; Back: |b| < u.

or: u = dot(b,c) / dot(b,b),

Front: u < 0; Between: 0 <= u <= 1; Back: 1 < u

It seems that with your definitions the point C is "between" A and B if angles CAB and ABC are both acute, front of A-B is angle CAB is obtuse, and behind of A-B if angle ABC is obtuse.

You can use the dot product to find if an angle is acute or obtuse: if XYZ is acute the doc product of XY·YZ is negative, and if it's obtuse the dot product is positive.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top