Direction to an object?

Hey

I need a vector from object A to object B, and then an angle between A’s forward and the vector to B.

I’ve tried to do it like this:

Vector3 aForward = a.transform.position + a.transform.forward;
Vector3 directionToB = b.transform.positon - a.transform.position;

Vector3.SignedAngle(aforwad, directionToB, Vector3.up);

However this doesn’t work. According to gizmos the direction vector varies wildly depending on where object A moves to, and the angle makes no sense. It changes based on object A’s location, and rotating A makes very little difference to it. (Also, I give forward and direction the same Y coordinate, they’re on the same global plane.)

I have no idea what I’m doing wrong.

Screens:

Hmm… So my first thought is, adding object A’s position plus it’s forward is really just a position, not a direction. That’d be like me taking one step (say one unit) forward in the +Z. If I was at (26, 3, 1) and my forward direction is (0, 0, 1), then my position plus my forward would be (26, 3, 2), the spot in front of me. So if you’d like to use A’s direction, I would use the transform’s forward.

The direction to B looks great – that’s B’s position - A’s position.

Now honestly, I never worked with their Vector3 helper methods, as in, I tend to do it more manually with formulas. But the angle between two vectors is part of the dot product relationship, and the two vectors in your case are A’s forward, and B - A. Sorry to drop formulas on you, but this is how I would get the final angle in degrees:

Vector3 aForward = a.transform.forward;
Vector3 dirToB = Vector3.Normalize(b.transform.position - a.transform.position);
float angle = Mathf.Rad2Deg * Mathf.Acos(Vector3.Dot(aForward, dirToB));

Let me know if you’d like me to explain the formula I used! The angle variable will be the (positive-only) angle between A’s forward and the direction from A to B in degrees, and will be in the range [0°, 180°]

Try:

Vector3.SignedAngle(a.transform.forward, directionToB, Vector3.up);