javascriptgeometry

Determining if one 2D vector is to the right or left of another


Given two 2D vectors, how can you tell whether the second is to the right (clockwise) of the first, or to the left (counter-clockwise)?

For instance, in these diagram B is to the right (counter-clockwise) of A

A   B   .       .----> A
^  ¬    |\      |   
| /     | \     |  
|/      V  \    V 
.       B   A   B

Solution

  • You can achieve this using a dot product. dot(a, b) == a.x*b.x + a.y*b.y can be used to find whether vectors are perpendicular:

    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")
    

    Put another way. dot > 0 tells you if a is "in front of" b.


    Assume b is on the right of a. Rotating b 90 degrees counterclockwise puts it in front of a.
    Now assume b is on the left of a. Rotating b 90 degrees counterclockwise puts it behind a.

    Therefore, the sign of dot(a, rot90CCW(b)) tells you whether b is on the right or left of a, where 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")