Check if a Point is between two Points

妖精的绣舞 提交于 2019-12-11 04:55:39

问题


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?


回答1:


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─────



回答2:


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



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/18171840/check-if-a-point-is-between-two-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!