检查一个点是否在两个点之间
我刚刚认识到我的数学有点生疏..我想检查一下Point C is between Point A and Point B
. C可以在A和B的线段上,也可以不在.可能有三种情况,我必须全部识别出来:
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在A和B之间
C is between A and B
C
/ \
A---B
C在A和B前面
C is in front of A and B
C
\ \
A--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.
我用点积检查C是否在A和B之间.
I used the dotproduct to check if C is between A and B.
if (VectorOf(AB) * VectorOf(BC)) >= 0)
要检查C是否在A和B的后面,请使用以下代码:
To check if C is in the back of A and B i use this:
if (VectorOf(AB) * VectorOf(BC)) < 0)
但是如何识别C是否在A和B前面?
But how to identify if C is in front of A and B?
只需使用从点B开始的点积.
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
}
}
或者,您可以计算相对于矢量AB的投影距离:
Alternatively, you can compute the projected distance, relative to vector AB :
(VectorOf(AC) * VectorOf(AB)) / (VectorOf(AB) * VectorOf(AB))
结果将是< 0,介于0和1之间,或者在三种情况下为> 1,如下所示:
The result would be < 0, between 0 and 1, or > 1 in your three cases, as shows the math below :
C
/│
/ │
/ │
──A── H ─────B─────
点积的定义是
AC · AB = AC×AB×cos(Â)= AH×AB(带符号:如果C留在A处,则为负;如果C留在A处,则为正.右).
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²(正数)
AB · AB = AB² (positive)
除法的结果是符号比AH/AB:
The result of the division is the signed ratio AH/AB :
- 0 1 >1
────A── H ─────B─────