Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[Question] Vector2 Angle

Discussion in 'Scripting' started by qVadro, Sep 12, 2018.

  1. qVadro

    qVadro

    Joined:
    May 18, 2017
    Posts:
    24
    Hi, i cannot figure out what I am doing wrong, but I can't get right angle using Vector2.Angle
    There is an example. My GameObject is on Canvas, panel is same size as screen, an with Vector2.Angle i get different angles depends on distance beetween that vectors.. Plz explain :)
    AngleInDeg works right!

    Code (CSharp):
    1. void Update ()
    2.     {
    3.         Vector2 mp = Input.mousePosition;
    4.         float wrongAngle = Vector2.Angle(transform.position, mp);
    5.         float angle = AngleInDeg(mp, transform.position) + 90;
    6.      
    7.         transform.rotation = Quaternion.identity;
    8.         transform.Rotate(new Vector3(0, 0, angle), Space.Self);
    9.      
    10.         Debug.DrawLine(mp, transform.position);
    11.  
    12.         A = angle;
    13.         ArrowPosition = transform.position;
    14.         MousePosition = mp;
    15.     }
    16.  
    17.     public static float AngleInRad(Vector3 vec1, Vector3 vec2)
    18.     {
    19.         return Mathf.Atan2(vec2.y - vec1.y, vec2.x - vec1.x);
    20.     }
    21.     public static float AngleInDeg(Vector3 vec1, Vector3 vec2)
    22.     {
    23.         return AngleInRad(vec1, vec2) * 180 / Mathf.PI;
    24.     }