Get rotation angle between object and Z axis

I’m working with Hololens 2 on Unity. Giving a point P, I would like to calculate the angle between the Z axis of my local coordinates system (where 0 is the origin: the position where I started the app) and this point P.
NB: I don’t want to get the angle based on the direction I’m facing, only between the axis and the vector3.
Sorry, I know maybe it’s an obvious question, but I’m a newbie of Unity.

Have a look at

What should I pass to the function? The game object P and my origin point?
Do this function care about the orientation of the object P?
Thanks!

You can pass in (0, 0, 1) and P.transform.position.

But this is just dot product. You probably want to know the following fact for the rest of your game development life:
dot(a, b) = (a.x * b.x + a.y * b.y + a.z * b.z) = length(a) length(b) cos(angle between a and b)

so in this case you want
arccos(dot((0, 0, 1), transform.position.normalized))

which is just
arccos(transform.position.normalized.z)

1 Like

As this is giving an angle between two vectors, you will probably want to supply (0,1) as the origin (i.e. a vector from the origin to y = 0 z = 1 and the position vector of the object (transform.position). The rotation of object P’s transform will not affect this, only its position.

Here is some sample code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AngleBetween : MonoBehaviour
{
    [SerializeField] Vector2 originDirection = new Vector2(0,1);

    private void Start()
    {
        Vector2 pos = new Vector2(transform.position.x, transform.position.z);
        Debug.Log(Vector2.SignedAngle(originDirection, pos).ToString("F3"));
    }

}

Edit: This line, Vector2 pos = new Vector2(transform.position.x, transform.position.z); is just for clarity and ease of messing about with the values. You can, of course, use transform.position directly.

Unfortunately, there is a known documentation error where it states the angle is clockwise, in fact the output follows mathematical convention with counter-clockwise being positive.

If you want to look at dot products, be aware that you can get Unity to do the work for you using Vector2.Dot

How much simplification you do depends on the type of output you need and how many quadrants you expect your object P to be in. For example, you can see in shelljump’s arccos(transform.position.normalized.z) that you will get the same angle and sign regardless of whether x < 0 or x > 0.