Search Unity

Question Calculating angle between two gameobjects in 2D game

Discussion in '2D' started by HanzlaJavaid, May 23, 2020.

  1. HanzlaJavaid

    HanzlaJavaid

    Joined:
    May 10, 2020
    Posts:
    3
    I'm trying to calculated angle between two gameobjects. One is a child of camera(target object) and the other one is independent(base object) .And the camera is moving right by the gameplay. Here is what my code looks like
    Code (CSharp):
    1. public static Vector3 getAngleTowardsPoint(GameObject targetObject,GameObject baseObject)
    2.      {
    3.          GameObject cam = GameObject.FindGameObjectWithTag("MainCamera");
    4.          Vector3 a = new Vector3(targetObject.transform.position.x + cam.transform.position.x, targetObject.transform.position.y + cam.transform.position.y);
    5.          Vector3 temp = a - baseObject.transform.position;
    6.          float Direction = Mathf.Atan2(temp.y, temp.x);
    7.          return new Vector3(0, 0, Direction*Mathf.Rad2Deg);
    8.      }
    This returns accurate vector unless I move child object of camera. As I move it in any way, this function returns wrong values. I have also tried with adding localposition of target object with camera object instead of simple position but result remained same. Looking forward for help. Thanks.
     
    viniciusandrade likes this.
  2. brigas

    brigas

    Joined:
    Oct 4, 2014
    Posts:
    522
    it seems like its because you are adding the transform of the camera to the target object, the position of the camera shouldn't exist in this formula if you don't want it to be a factor.

    What you want in this case is to compare always the world positions of the objects
     
  3. HanzlaJavaid

    HanzlaJavaid

    Joined:
    May 10, 2020
    Posts:
    3
    Thanks for reply. You are right, and I was also messing up by referencing prefab to target instead of game object.