Search Unity

angle for animation calculated from a right triangle

Discussion in '2D' started by ouzer, Apr 21, 2017.

  1. ouzer

    ouzer

    Joined:
    Apr 15, 2017
    Posts:
    1
    I've been making a top down game where the Zombie (red) tries to kill The Fighter (blue). For animations I need to know the angle between them. I've tried this code where the angle is calculated from a right triangle. I'm somehow receiving wrong results and I don't know why.
    Script is attached to zombie.

    I'm not sure if there is better method out there, but if you know one, please inform me about it.
    Thanks :)


    Code (CSharp):
    1.       Hypotenuse = Vector2.Distance(transform.position, Fighter.transform.position);
    2.         Cathetus_End_pos = new Vector2 (transform.position.x , Mathf.Abs (Fighter.transform.position.y - transform.position.y));
    3.         Cathetus = Vector2.Distance(transform.position , Cathetus_End_pos);
    4.         AngleInDeg = Mathf.Cos(Cathetus / Hypotenuse) * Mathf.Rad2Deg;
    5.         Debug.Log("Angle:"+AngleInDeg.ToString());
    6.         Debug.Log("Hypotenuse:" + Hypotenuse.ToString());
    7.         Debug.Log("cathetus:" + Cathetus.ToString());
     
    Last edited: Apr 22, 2017
  2. steego

    steego

    Joined:
    Jul 15, 2010
    Posts:
    969
    Assuming your green cathetus in the image is pointing in the world up direction, this will give you the angle between them:

    Code (csharp):
    1. float angle = Vector2.Angle(Vector2.up, (Fighter.transform.position - transform.position));
    However I guess what you really want in this case is the signed angle, you can find that like this

    Code (csharp):
    1.  
    2. Vector2 direction = (Fighter.transform.position - transform.position);
    3. float angle = Vector2.Angle(Vector2.up, direction);
    4. Vector3 cross = Vector3.Cross(Vector2.up, direction);
    5. if (cross.z > 0)
    6. {
    7.     ang = 360 - ang;
    8. }
    9.