# Calculating relative position with cross product

Discussion in 'Scripting' started by Sendatsu_Yoshimitsu, Jul 27, 2019.

1. ### Sendatsu_Yoshimitsu

Joined:
May 19, 2014
Posts:
673
I'm trying to calculate if one line segment is to the left or right-hand side of another segment. My understanding is that, given that both segments are on the x,z axes, if I take the cross of one line's start and endpoints relative to the second line's direction, the sign of the result's y-value should always be negative if the second line is on the left, and positive if it's on the right:

Code (CSharp):
1.
2.    public class LineSegment
3.     {
4.         Vector3 p0; //start point
5.         Vector3 p1; //end point
6.
7.         public bool IsLeft(LineSegment lineSegment)
8.         {
9.             return Vector3.Cross(p1 - p0, lineSegment.p0).y <= 0 && Vector3.Cross(p1 - p0, lineSegment.p1).y <= 0;
10.         }
11.     }
12.
However, in practice this always seems to return false; am I grossly mis-understanding how Vector3.Cross is supposed to be used?

Last edited: Jul 27, 2019

Joined:
Apr 13, 2014
Posts:
826
Cross Product takes two vectors, you are giving it a vector and a "point".

You need to cross the vector of
``p1 - p0``
with the vector of
``other.p0 - p0``
to get the proper result.

Code (CSharp):
1. Vector3.Cross(p1 - p0, lineSegment.p0 - p0).y <= 0

3. ### Sendatsu_Yoshimitsu

Joined:
May 19, 2014
Posts:
673
Oops, that was a really obvious mistake on my part- thank you for the clarification!! unityunity