Search Unity

Working with angles in 2D

Discussion in '2D' started by oliver_unity892, Dec 17, 2020.

  1. oliver_unity892

    oliver_unity892

    Joined:
    Oct 28, 2019
    Posts:
    91
    Hi

    I have the following code which gives me an angle of direction between two vectors. However, the angle is only ever 0 to 180, whether the direction is on the left, or the right of the scripted object. I need it to go from 0 to 360 so that I can clearly indentify whether the direction is to the left, right, back, front etc.

    Code (CSharp):
    1.     public void SetDirection(Vector2 newDirection)
    2.     {
    3.  
    4.         Vector2 tempLocation = transform.localPosition;
    5.         Vector2 tempVector = newDirection - tempLocation;
    6.  
    7.         float angleRadians = Mathf.Atan2(tempVector.y, tempVector.x);
    8.         angleDegrees= angleRadians * Mathf.Rad2Deg;
    9.  
    10. }
    angleDegrees is only ever 0 to 180. Need it to be 0 to 360.

    Any ideas?
     
  2. raarc

    raarc

    Joined:
    Jun 15, 2020
    Posts:
    535
    it goes from -180 to 180, check for the negative values.

    if you really want it to be 0 through 360 add 180 to your final angle
     
    eses likes this.
  3. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637