# Directional vector question

This topic is 2538 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi all,

I was just wondering how to go about determining what side a particular object is in regards to a 2d directional vector. (I.e. is it to the left or right?)

Thanks

##### Share on other sites
My favorite solution uses complex numbers: If your object is at z and your direction vector is w, you can compute z*conj(w) and look at the sign of the imaginary part.

R. Sedgewick refers to a function that does something similar as "CCW" (for "CounterClockWise"). Given three points, it tells you which way the turn they describe goes. You can search for it.

##### Share on other sites
You can do this very simply with a perp-dot product.

Given the object to be queried at 'b' and the object where you are standing 'a' and direction 'd', you compute

(b-a) perpdot d

and check the sign of the value.

perpdot between two vectors (x1,y1) and (x2,y2) is x1*y2 - y1*x2

##### Share on other sites
Aloha,

Let’s say your line is defined by the points A and B. In order to find out whether a point C is on the left or right you can look at the sign of the following determinant:
[Formula] \begin{vmatrix} B.x-A.x & C.x-A.x\\ B.y-A.y & C.y-A.y \end{vmatrix} [/Formula]
If positive C is left, if negative it is right, if zero all three a collinear.

Or in code:
bool isLeft(Vector2 A, Vector2 B, Vector2 C){ return ((B.x - A.x)*(C.y - A.y) - (B.y - A.y)*(C.x - A.x)) > 0; }

That’s a very cheap test actually and it is quite common in computational geometry.
Hope that helps.

Edit: Too slow. That's exactly what luca-deltodesco just said. You beat me to it, buddy.

##### Share on other sites
Thats great! Thank you all for your help.

1. 1
2. 2
Rutin
21
3. 3
4. 4
A4L
15
5. 5
khawk
14

• 13
• 26
• 10
• 11
• 44
• ### Forum Statistics

• Total Topics
633742
• Total Posts
3013631
×