Search Unity

math / vector problems

Discussion in 'Scripting' started by raoul, Sep 22, 2008.

  1. raoul

    raoul

    Joined:
    Jul 14, 2007
    Posts:
    6,735
    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.

    Code (csharp):
    1.  
    2. // get direction of cube2
    3. cube2dir1 = cube2.position - oldPos;
    4. // switch x and z values
    5. cube2dir2 = Vector3(cube2dir1.z, cube2dir1.y, cube2dir1.x);
    6.  // get vector between cubes
    7.   cubesdir = cube1.position - cube2.position;
    8.  if (Vector3.Dot(cube2dir2,cubesdir) < 0)
    9.        print ("on the left" + Vector3.Dot(cube2dir2,cubesdir));
    10. else
    11.        print ("on the right" + Vector3.Dot(cube2dir2,cubesdir));
    12.  
    13. oldPos = cube2.position;
    14.  
    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
     
  2. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    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.
     
  3. HiggyB

    HiggyB

    Unity Product Evangelist

    Joined:
    Dec 8, 2006
    Posts:
    6,183
    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.
     
  4. raoul

    raoul

    Joined:
    Jul 14, 2007
    Posts:
    6,735
    Thanks Andeeee! The below seems to give the right result, got to do some more testing:

    Code (csharp):
    1.  
    2. var heading = cube2.forward;
    3. var cubesdir = cube1.position - cube2.position;
    4. var vCross = Vector3.Cross(heading, cubesdir);
    5.