# math / vector problems

Hi all,

I need to find out whether an object is on the left or right of a moving rigidbody. I setup at test project with just 2 cubes to figure out how to solve this. cube2 is moved manually in the scene editor while running the scene). Maybe I am making things over complicated but I thought the below should give the right result and I can´t think of another way to solve this.

``````// get direction of cube2
cube2dir1 = cube2.position - oldPos;
// switch x and z values
cube2dir2 = Vector3(cube2dir1.z, cube2dir1.y, cube2dir1.x);
// get vector between cubes
cubesdir = cube1.position - cube2.position;
if (Vector3.Dot(cube2dir2,cubesdir) < 0)
print ("on the left" + Vector3.Dot(cube2dir2,cubesdir));
else
print ("on the right" + Vector3.Dot(cube2dir2,cubesdir));

oldPos = cube2.position;
``````

It does work right when moving cube2 over the z-axis, it gives opposite results when moving the cube over the x-axis. When, for example rotating cube2 45 degrees and the result changes when the angle between the moving direction of cube2 and cube1 and the vector between cube1 and cube2 is 90 degrees.

I am not sure where this goes wrong or what else to try. Anyone knows how to do this?

Many thanks,
Raoul

Get the rigidbody object’s forward direction (using transform.forward) and the heading of the other object using vector subtraction as you did in your posted code. Then, use Vector3.Cross to get the cross product of the two vectors - pass the forward vector as the first parameter and the heading vector as the second. You will get a Vector3 as a result - the Y component will be negative if the other object is to the left, positive if it is to the right and zero if it is straight ahead.

andeeee FTW!

Let us know if you need help turning the above suggestion into code as it’s definitely the way to go about it. Just to add, you might also need to consider the case when the cross-product’s result has a zero y-component which indicates that it’s either directly ahead of or behind the moving object.

Thanks Andeeee! The below seems to give the right result, got to do some more testing:

``````var heading = cube2.forward;
var cubesdir = cube1.position - cube2.position;