Skip to content

Instantly share code, notes, and snippets.

@smkplus
Last active January 22, 2018 08:56
Show Gist options
  • Save smkplus/777a58bec9ff5a3f6271ab1f6b5f10c2 to your computer and use it in GitHub Desktop.
Save smkplus/777a58bec9ff5a3f6271ab1f6b5f10c2 to your computer and use it in GitHub Desktop.
Get Angle between two vector and debug it

directions

 using UnityEngine;
 using System.Collections;
 
 public class AngleDebugger : MonoBehaviour
 {
     public Transform target;
     private float Angle;
 
 
     void Update()
     {  
         Angle = GetAngle(transform.position,target.position);
         DebugAngle();
     }
 
     public float GetAngle(Vector2 A,Vector2 B)
     {
         //difference
         var Delta = B - A;
         //use atan2 to get the angle; Atan2 returns radians
         var angleRadians = Mathf.Atan2(Delta.y, Delta.x);
 
         //convert to degrees
         var angleDegrees = angleRadians * Mathf.Rad2Deg;
 
         //angleDegrees will be in the range (-180,180].
         //I like normalizing to [0,360) myself, but this is optional..
         if (angleDegrees < 0)
             angleDegrees += 360;
 
         return angleDegrees;
     }
 
 
     void DebugAngle()
     {
         if (Between(60, 120))
             {
             print("N");
         }
         if (Between(240, 300))
         {
             print("S");
         }
         if (Between(330, 360) || Between(0, 30))
         {
             print("E");
         }
         if (Between(150, 210))
         {
             print("W");
         }
 
 
         if (Between(120, 150))
         {
             print("NW");
         }
         if (Between(30, 60))
         {
             print("NE");
         }
 
         if (Between(210, 240))
         {
             print("SW");
         }
         if (Between(300, 330))
         {
             print("SE");
         }
 
 
     }
 
     bool Between(float A,float B)
     {
         if(Angle < B && Angle > A)
         {
             return true;
         }
         return false;
     }
 
 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment