Search Unity

Offseting 90° to the direction of a vertice

Discussion in 'Scripting' started by itsDmajster, Nov 25, 2014.

  1. itsDmajster

    itsDmajster

    Joined:
    Oct 27, 2014
    Posts:
    45
    Hello!

    take a look at this picture.


    how would i be able to offset some vector3 points so they only offset in the direction of the blue line? The blue line is always 90° to the left of the direction that is looking towards the targeted point. Any help would be appreciated!

    Dmajster
     
  2. Stoven

    Stoven

    Joined:
    Jul 28, 2014
    Posts:
    171
    This piece of code takes a Vector and rotates its direction left or right in a 90 degree angle.

    This will only work for 2D scenarios.

    Code (CSharp):
    1.  
    2.  
    3.     public enum PDirection { LEFT, RIGHT };
    4.  
    5.     public static Vector2 PerpVector2D(Vector2 original, PDirection dir = PDirection.LEFT)
    6.     {
    7.  
    8.         Vector2 vec = new Vector2(0, 0);
    9.  
    10.         if (dir == PDirection.LEFT)
    11.         {
    12.  
    13.             vec.x = original.y * -1;
    14.             vec.y = original.x;
    15.         }
    16.         else
    17.         {
    18.  
    19.             vec.x = original.y;
    20.             vec.y = original.x * -1;
    21.         }
    22.  
    23.         return vec;
    24.     }
    If you need a 3D solution, you'll need more information since there are infinitely many vectors that can satisfy being 90 degrees from the Vector generated by any 2 points in space.
     
    Last edited: Nov 25, 2014
    itsDmajster likes this.
  3. itsDmajster

    itsDmajster

    Joined:
    Oct 27, 2014
    Posts:
    45
    I am currently working in a 2d environment so this will be of great help, may i ask how do i use it ?
     
  4. Stoven

    Stoven

    Joined:
    Jul 28, 2014
    Posts:
    171
    If you perform the operation 'target vertex minus a vertex position' you will get a vector that has a magnitude equal to the distance between the two points and the direction that represents the direction from the vertex position to the target vertex.

    That is your original Vector. Simply supply it to the PerpVector2D function with the desired direction argument. The result Vector2 will be the direction rotated either to the left or right of that direction, depending on the value of dir.
     
    itsDmajster likes this.
  5. itsDmajster

    itsDmajster

    Joined:
    Oct 27, 2014
    Posts:
    45
    Oh, i get it now! Thank you!