Check if a point is on the right or left of a vector?
I have vector BA and a point C ( in a 3D world but assume they all have same Y).
How do i check if C is on the right or the left of vector BA
Answer by tanoshimi · Jan 21, 2017 at 02:23 PM
You could calculate this by testing the sign of the Cross Product between the vectors BA and BC. Or if you're only operating in 2D space, try this...
bool IsLeft(Vector2 A, Vector2 B)
{
return -A.x * B.y + A.y * B.x < 0);
}
How is this the answer? The formula doesn't even include point C, how could it test if it's on the left or right of anything?
Answer by The_Pied_Shadow · Dec 29, 2020 at 02:00 PM
To do this it's safe to assume we're thinking about these points in 2D space. If you want to determine a left or right of line you have to define what exactly left or right means. Is left positive y? positive z? Unity considers 'left' to be in the negative x direction and 'right' in the positive x direction whether in world or local space. For this answer I'll assume the same I just wanted to make note of it so if someone was operating on a different 2D plane assumption they would need to adjust the formula accordingly.
Vector3 vec = A.position - B.position;
Vecotr3 dir = C.position - B.position;
Vector3 cross = Vector3.Cross(vec, dir);
Here 'vec' represents a the vector you want to test the location relative to. 'Dir' is a vector from the origin position of 'vec' to the point you want to check.
In this case, the y value of the variable 'cross' will be positive when on the right side of the line and negative when on the left. This is relative to the direction of the line (in this case from point B looking at point A). So in the diagram you showed, if you plugged the positions of all these points in then the cross product would have a negative value for C.