Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Finding an angle between two objects? (Is my player facing this object?)

Discussion in 'Scripting' started by Marscaleb, May 11, 2021.

  1. Marscaleb

    Marscaleb

    Joined:
    Jan 7, 2014
    Posts:
    1,036
    I'm trying to figure out if the player is facing an object or not (within a given range.)

    So I have: a player and another object, an angle in degrees that the player is facing, and a variable for how far off the player can be.
    I previously made some code where I checked the player's angle compared to an arbitrary angle, which was
    if (Mathf.DeltaAngle(DaPlayer.ShareMyFacingAngle(), (float)ladderDirection) < 15f)
    . (Although for some reason I seem to get more "true" results from one side than the other. Never figured out why but it worked good enough so I didn't care.)
    I figure I could do the same thing, but to pull that off I would need an angle between the player and the object.

    How would I get the angle between the player's position and the object's position, along the XZ axis?

    Or for that matter, would there be a simpler way to find if my player is facing this other object or not?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    I would take the player's
    transform.forward
    , copy it out, zero the Y field so it is flat on XZ.

    Then I would subtract the player position from the object position in question, giving you a vector to it.

    Zero out the Y field in that one too so it is flat XZ.

    Now you have two flat vectors: one your nose and one the bearing to the thing of interest.

    Feed those two vectors into Vector3.Angle() and there's your angle.
     
  3. If you want to check if something is facing something else, then you use dot product. Since Freya is excellent teacher and she has a cool class on it, I link it to you instead of trying to explain properly how it works. This should get you approximately at the timestamp you need, but I urge you to watch the entire video and the series later, it's one of the best primer in vector-math.

     
    Munchy2007 likes this.