Search Unity

Looking at percentage?

Discussion in 'Scripting' started by mikelowefedex, Nov 27, 2020.

  1. mikelowefedex

    mikelowefedex

    Joined:
    Sep 29, 2020
    Posts:
    139
    Hello,
    I was wondering if there is a quick and easy way to calculate if an object is looking at a vector so I get a -1 if the object is facing away, a 0 if the object is facing to the side, and a 1 if the object is looking directly at the vector. Is there a single Vector3 function for that? Thank you.
     
  2. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,990
    Yes, it's called the dot product which is one of the fundamental operations you can do with vectors besides adding them. Unity's Vector3 struct has a static method to calculate the dot product: Vector3.Dot. Note that in order to get your desired value range both vectors need to be normalized (i.e. unit vectors). The "forward" vector of the Transform component is a normalized vector which points in the positive z direction (the blue arrow in the scene view when you select the object in "local" gizmo mode).

    The dot product between two unit vectors is 1 if both vectors are identical and -1 if they point in opposite directions. The dot product is 0 if the two vectors are perpendicular to each other.
     
    Vryken likes this.
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    However, note that the dot product is not linear between those values. e.g. a difference of 45 degrees does NOT give a dot product of 0.5.

    If you want the actual angle, you can use Vector3.Angle
     
  4. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,990
    Yes, the dot product between to vectors actually returns the cosine between the two vectors multiplied by the length of both vectors. When the two vectors are normalized you directly get the cosine of the angle between the two vectors. You can use the Acos function to calculate the angle in radians. This is what Vector3.Angle actually does.
     
  5. mikelowefedex

    mikelowefedex

    Joined:
    Sep 29, 2020
    Posts:
    139
    Thank you. I was able to figure out how to get what I needed, done.