您可以计算由三个点定义的三角形形成的有符号面积 - 这相当于表示边缘的向量的 2D“叉积”(有时称为 perp 积):
这是一个简单的python实现,显示了计算;您可以在闲暇时将其转录为 C++。
从那里,交换三角形中两点的位置会将转角从ccw 反转为cw,反之亦然
class CollinearpointsError(ValueError):
pass
def ccw(triangle):
"""returns True if the triangle points are counter clock wise,
False otherwise, and raises a CollinearpointsError when the
three points are collinear
"""
A, B, C = triangle
ax, ay = A
bx, by = B
cx, cy = C
AB = (bx - ax, by - ay)
AC = (cx - ax, cy - ay)
a, b = AB
c, d = AC
signed_area_x2 = a * d - b * c
if signed_area == 0:
raise CollinearpointsError('the three points are collinear')
return (a * d - b * c) > 0
def cw(triangle):
"""returns True if the triangle points are clock wise,
False otherwise, and raises a CollinearpointsError when the
three points are collinear
"""
return not ccw(triangle)
A = (0, 0)
B = (0, 1)
C = (1, 0)
triangle = (A, B, C)
print(cw(triangle))
triangle = (A, C, B)
print(cw(triangle))
triangle = (A, B, (0, 2))
print(cw(triangle))
输出:
True
False
CollinearpointsError: the three points are collinear