Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

2D Mathf determine Vector direction

Discussion in '2D' started by _jacks, Aug 22, 2015.

  1. _jacks

    _jacks

    Joined:
    Nov 27, 2014
    Posts:
    27
    Hello

    I need to find out how to get a direction of a Vector in 2D. Eg. North, South, East, West

    If you can imagine two objects one is blue and the other is black. The blue one is static but the black one can move around as time goes by so I need to figure out where the black object is at any point and return a direction. I'm just not sure how to go about it.

    Basically I have a sprite which requires it looks at the player when something hits the collider. The easiest way I could figure to do this with the animation system was to create directions and have the sprite face that direction so it appears to look at the object.

    So my question is how can you determine direction of a vector from the static object on the X or Y axis
     
  2. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    try, black position minus blue positon. I think you should then get the direction from blue to black.

    or use LookAt :D Unfortunately, the function is for 3d. And works with z-axe (but default gameobject can be rotated in editor). Maybe there is something similar in 2d, i dont know.
     
    Last edited: Aug 22, 2015
  3. tedthebug

    tedthebug

    Joined:
    May 6, 2015
    Posts:
    2,570
    You can't use vector3.lookat & clamp the axis you don't want it to rotate around?
     
  4. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    897
    The following will give you the angle between two object.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Direction : MonoBehaviour
    5. {
    6.     public GameObject trace;
    7.  
    8.     void Update ()
    9.     {
    10.         Vector2 dir = trace.transform.position - transform.position;
    11.         float angle = Mathf.Atan2(dir.y, dir.x)*Mathf.Rad2Deg;
    12.  
    13.         Debug.Log(angle);
    14.     }
    15. }
    16.  
     
  5. _jacks

    _jacks

    Joined:
    Nov 27, 2014
    Posts:
    27
    Thanks.