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. Dismiss Notice

Calculate angle between a characters facing direction and a position

Discussion in 'Scripting' started by TheCelt, Aug 22, 2016.

  1. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    718
    Hello

    I was wondering what is the simplest way to get the angle between the character's facing direction (transform.forward) and a vector3 position in the game world?

    Wanting to work out if the position is behind the character and by how much to determine which turning animation i should use.
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    Transform.InverseTransformPoint(someWorldVector) will give you the relative direction and magnitude in local space compared to the Transform's forward position. To figure out if it's "behind the character", you'd just test that the Z value is negative, I believe, and you can determine distance from the magnitude. If you want a cone-like shape as an area to test, just make sure the absolute value of Z is greater than the absolute values of X and Y, and it'll be "more behind you than to the side", assuming Z is negative. These simple kinds of logic checks can do wonders if you don't need precise results.

    The angle could be specifically calculated just with Vector3.Angle(Vector3.zero, someLocalVector) I believe, or vice-versa for the inverse. I haven't done this kind of thing though, so I'm sure someone will correct me if I'm wrong.
     
    Last edited: Aug 23, 2016
    lloydsummers likes this.
  3. lloydsummers

    lloydsummers

    Joined:
    May 17, 2013
    Posts:
    343
    I'd say you covered it well :) Technically, if both are 3D transformational positions, you could just get away with Vector3.Angle.
     
  4. Boz0r

    Boz0r

    Joined:
    Feb 27, 2014
    Posts:
    419
    You don't need to use InverseTransformPoint. You get a unit vector pointing towards the position from (position - transform.position).normalized(), and then you can get the angle between these to vectors by Vector3.Angle().

    Code (CSharp):
    1. Vector3 toPosition = (position - transform.position).normalized();
    2. float angleToPosition = Vector3.Angle(transform.forward, toPosition);
    That's probably the simplest way.

    EDIT: I just checked the documentation, and it looks like you don't even need to normalize the vector, the Angle() method probably does it too. They documentation for Angle() also has an example that's exactly what you're trying to do:

    http://docs.unity3d.com/ScriptReference/Vector3.Angle.html
     
    Last edited: Aug 23, 2016
    kitakika and lloydsummers like this.