如何判断一个点是在线段的左边还是右边?
How to tell if a point is on the left or right side of a line segment?
如果我们有一条线段(A.x, A.y, B.x, B.y)
和一个点(C.x, C.y)
,我如何判断该点是在线段的左侧还是右侧,顶部还是底部?我已经尝试过涉及以前帖子中交叉产品的解决方案,但它让我遇到了另一个问题。使用叉积使得 A 和 B 的顺序很重要。还有什么方法可以让A和B的顺序无所谓?
以前帖子的解决方案:
Use the sign of the determinant of vectors (AB,AM), where M(X,Y) is the query point:
position = sign((Bx - Ax) * (Y - Ay) - (By - Ay) * (X - Ax))
It is 0 on the line, and +1 on one side, -1 on the other side.
来源:How to tell whether a point is to the right or left side of a line
(我假设是笛卡尔坐标系,正x和y分别指向右边和上面)
给定一条通过点 (a, b), (c, d) 的直线,其方程为:
现在你有一个点(e, f)。如果你代入x=e, y=f, 并且它们满足等式,那就意味着这个点在直线上。
如果等式的左边较大,则表示您的点位于直线的顶部。如果等式右边较大,说明你的点在直线下方。
要计算出left/right,您还需要考虑梯度。如果梯度为正,则位于线下方意味着您位于线的右侧。如果梯度为负,则位于线下方意味着您位于线的左侧。反之亦然。
请注意,您需要将垂直线作为一种特殊情况进行处理。
在Java,
double lhs = e;
double gradient = (b - d)/(a - c);
if (Double.isInfinite(gradient)) {
// vertical line, compare only x coordinates
if (e < a) {
// on the left
} else if (e > a) {
// on the right
} else {
// on the line
}
}
double rhs = (gradient * (e - a)) + b;
if (lhs > rhs) {
if (gradient > 0) {
// on the left
} else if (gradient < 0) {
// on the right
} else {
// on the top
}
} else if (lhs < rhs) {
if (gradient > 0) {
// on the right
} else if (gradient < 0) {
// on the left
} else {
// below
}
} else {
// on the line
}
要证明重新排列点的顺序不会改变这个结果很简单。改变点的顺序产生这个等式(a 变为 c,b 变为 d):
如果将上面的方程式和开头的方程式展开,你会发现它们实际上是同一个方程式,即:
如果我们有一条线段(A.x, A.y, B.x, B.y)
和一个点(C.x, C.y)
,我如何判断该点是在线段的左侧还是右侧,顶部还是底部?我已经尝试过涉及以前帖子中交叉产品的解决方案,但它让我遇到了另一个问题。使用叉积使得 A 和 B 的顺序很重要。还有什么方法可以让A和B的顺序无所谓?
以前帖子的解决方案:
Use the sign of the determinant of vectors (AB,AM), where M(X,Y) is the query point:
position = sign((Bx - Ax) * (Y - Ay) - (By - Ay) * (X - Ax))
It is 0 on the line, and +1 on one side, -1 on the other side.
来源:How to tell whether a point is to the right or left side of a line
(我假设是笛卡尔坐标系,正x和y分别指向右边和上面)
给定一条通过点 (a, b), (c, d) 的直线,其方程为:
现在你有一个点(e, f)。如果你代入x=e, y=f, 并且它们满足等式,那就意味着这个点在直线上。
如果等式的左边较大,则表示您的点位于直线的顶部。如果等式右边较大,说明你的点在直线下方。
要计算出left/right,您还需要考虑梯度。如果梯度为正,则位于线下方意味着您位于线的右侧。如果梯度为负,则位于线下方意味着您位于线的左侧。反之亦然。
请注意,您需要将垂直线作为一种特殊情况进行处理。
在Java,
double lhs = e;
double gradient = (b - d)/(a - c);
if (Double.isInfinite(gradient)) {
// vertical line, compare only x coordinates
if (e < a) {
// on the left
} else if (e > a) {
// on the right
} else {
// on the line
}
}
double rhs = (gradient * (e - a)) + b;
if (lhs > rhs) {
if (gradient > 0) {
// on the left
} else if (gradient < 0) {
// on the right
} else {
// on the top
}
} else if (lhs < rhs) {
if (gradient > 0) {
// on the right
} else if (gradient < 0) {
// on the left
} else {
// below
}
} else {
// on the line
}
要证明重新排列点的顺序不会改变这个结果很简单。改变点的顺序产生这个等式(a 变为 c,b 变为 d):
如果将上面的方程式和开头的方程式展开,你会发现它们实际上是同一个方程式,即: