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
You can achieve this using a dot product.
dot(a, b) == a.x*b.x + a.y*b.ycan be used to find whether vectors are perpendicular:Put another way.
dot > 0tells you ifais “in front of”b.Assume
bis on the right ofa. Rotatingb90 degrees counterclockwise puts it in front ofa.Now assume
bis on the left ofa. Rotatingb90 degrees counterclockwise puts it behinda.Therefore, the sign of
dot(a, rot90CCW(b))tells you whether b is on the right or left of a, whererot90CCW(b) == {x: -b.y, y: b.x}.Simplyifying: