Rotation angle from one object to another

Hi,

I’m trying to ge the rotation angle from my transform to another object.

Here’s a little picture to describe what I mean

What I’m trying to achieve is the following:
Get the rotation angle from my transform to another gameobject.
So that 0° is forward of my transform (The biggest cube in this case).
C#

Please let me know if I haven’t explained this good enough :slight_smile:

Thanks, Andreas.

Hi, this should work.

Vector3 direction = (target - transform.position).normalized;
float angle = Vector3.Angle (direction, unit.transform.forward);

If I get what you’re asking this is a simple task. You want the angle between the direction the first cube is looking and the position of the other cube? Then it’s something like

Vector3.AngleBetween( object 1 forward, object 1 position - object 2 position  );

A simple Vector3.Angle call will work here, but usually when I do this I want to know what the angle between them in relation to some plane. If you were to do this:

Vector3.Angle(transform.forward, other.position - transform.position);

You will get the angle between the two through a plane defined by, I think, the first point and the cross product between the two vectors. If the objects are always on the same plane, that’s fine, it’ll be the same thing. However if one object is elevated above the grid in your image then the angle will not be the same, and the further the object is away from the grid plane the more wrong the result of his function will be.

So instead you can do the same thing, but project the vectors onto a know plane, in this case a plane defined by Vector3.up.

var angle = Vector3.Angle(
  Vector3.ProjectOnPlane(transform.forward, Vector3.up).normalized,
  Vector3.ProjectOnPlane(other.position - transform.position, Vector3.up).normalized
);

So I keep getting 90 degrees no matter what.

I know this is really dumb, but I just create a dummy object then do LookAt() and then you just subtract the angle of the first gameObject from the dummy gameObject. This wouldn’t be good for operating every single frame though, but you could just have a dummy object for general purposes and to LookAt() then just subtract the transform.eulerAngle.y’s from each other.