确定一个2D矢量是否在另一个的右侧或左侧

Eri*_*ric 3 javascript geometry

给定两个2D向量,如何判断第二个向右(顺时针)第一个,还是向左(逆时针)?

例如,在这些图中,B是A的右侧(逆时针)

A   B   .       .----> A
^  ¬    |\      |   
| /     | \     |  
|/      V  \    V 
.       B   A   B
Run Code Online (Sandbox Code Playgroud)

Eri*_*ric 31

您可以使用点积来实现此目的.dot(a, b) == a.x*b.x + a.y*b.y可用于查找矢量是否垂直:

var dot = a.x*b.x + a.y*b.y
if(dot > 0)
    console.log("<90 degrees")
else if(dot < 0)
    console.log(">90 degrees")
else
    console.log("90 degrees")
Run Code Online (Sandbox Code Playgroud)

换一种方式.dot > 0告诉你是否a"在前面" b.


假设b在右侧a.b逆时针旋转90度将其置于前方a.
现在假设b在左边a.b逆时针旋转90度使其落后a.

因此,dot(a, rot90CCW(b))告诉你b是在a的右边还是左边的标志rot90CCW(b) == {x: -b.y, y: b.x}.

Simplyifying:

var dot = a.x*-b.y + a.y*b.x;
if(dot > 0)
    console.log("b on the right of a")
else if(dot < 0)
    console.log("b on the left of a")
else
    console.log("b parallel/antiparallel to a")
Run Code Online (Sandbox Code Playgroud)