Rotate object on z axis to look at Vector3

I thought I had a handle on this, but clearly I don’t!

I have an empty object with two sprites as children. I want to rotate the empty object to face a Vector3 on the z axis only. I seem to be rotating on other axis and not on z. Here is a bit of code I’ve tried, I’ve also tried many variations. I need to prevent rotation on x and y.

Vector3 targetPosition = targetTransform.position
targetPosition.z = transform.position.z
transform.LookAt(targetPosition);

So this is basically a 2D situation, where you want to keep your objects in X and Y and rotate only around Z.

LookAt’s not really made for that; it assumes that you want to rotate around the object’s local Y axis. You could probably make it work by jumping through some hoops, but…

For this sort of thing, I usually use this method:

  /// <summary>
   /// Returns the signed angle between this 3D vector and another,
   /// with respect to some orthogonal "up" vector.  If looking in
   /// the "up" direction, then + angles are counter-clockwise.
   /// </summary>
   /// <returns>The signed angle, in degrees, from A to B.</returns>
   /// <param name="a">Vector this was called on.</param>
   /// <param name="b">Vector to measure the angle to.</param>
   public static float SignedAngleTo(this Vector3 a, Vector3 b, Vector3 up) {
     return Mathf.Atan2(
       Vector3.Dot(up.normalized, Vector3.Cross(a, b)),
       Vector3.Dot(a, b)) * Mathf.Rad2Deg;
   }

This lets you find the angle between two vectors, as rotated around anything axis you like. In your case you’d do something like:

float angle = Vector3.right.SignedAngleTo(targetPosition - transform.position, Vector3.forward);

Specifying Vector3.forward for the last parameter tells the function to consider the forward vector (i.e. 0,0,1) to be “up” for the purposes of this angle measurement. And then it returns the degrees between right (i.e. 1,0,0) and a vector that points at the target.

Then you would just set the rotation of your object accordingly, e.g. transform.eulerAngles = new Vector3(0, 0, angle).

HTH,

  • Joe
1 Like

Thanks Joe,

Did a copy and paste job on your code in hopes I might understand your vector math, but got an error with the line below. ‘Vector3 has no reference to SignedAngleTo’.

I tried to search for other code to find angle as you pointed out I should be using transform.eulerAngles, but had issues with those also. Some posts claimed their code fails when angle is zero, but I don’t think that’s where I’m seeing the problem. I can get the correct angle sometimes and other times it is about 75° off.

The code I’m using is not on the object I’m rotating. My target Vector3 is randomly created with a fixed z position. The object I’m rotating is also positioned randomly prior to the rotate function and also has it’s z position set to the same z value of the target. I’ve been tinkering around with this problem for a while now and it seems the more I fiddle with it the less I’m understanding as the results do not match what I’m expecting.

Hmm, maybe you didn’t paste my code in the right place. This is an extension method; it effectively adds a new method to Vector3 instances (thanks to the this modifier on the first parameter). But you have to put it somewhere that’s in scope for where you’re trying to use it. What I do is make a whole static class of related extension methods, e.g.:

public static class VectorExtensions {

    /// <summary>
    /// Returns the signed angle between this 2D vector and another.
    /// (This is unlike Vector2.Angle, which always returns the
    /// absolute value of the angle.)
    /// </summary>
    /// <returns>The signed angle, in degrees, from A to B.</returns>
    /// <param name="a">Vector this was called on.</param>
    /// <param name="b">Vector to measure the angle to.</param>
    public static float SignedAngleTo(this Vector2 a, Vector2 b) {
        return Mathf.Atan2( a.x*b.y - a.y*b.x, a.x*b.x + a.y*b.y ) * Mathf.Rad2Deg;
    }
   
    /// <summary>
    /// Returns the signed angle between this vector and the +X axis.
    /// </summary>
    /// <returns>The signed angle, reprenting the direction of this in degrees.</returns>
    /// <param name="a">Vector this was called on.</param>
    public static float SignedAngle(this Vector2 a) {
        return Mathf.Atan2( a.y, a.x ) * Mathf.Rad2Deg;
    }
   
    /// <summary>
    /// Returns the signed angle between this 3D vector and another,
    /// with respect to some orthogonal "up" vector.  If looking in
    /// the "up" direction, then + angles are counter-clockwise.
    /// </summary>
    /// <returns>The signed angle, in degrees, from A to B.</returns>
    /// <param name="a">Vector this was called on.</param>
    /// <param name="b">Vector to measure the angle to.</param>
    public static float SignedAngleTo(this Vector3 a, Vector3 b, Vector3 up) {
        return Mathf.Atan2(
            Vector3.Dot(up.normalized, Vector3.Cross(a, b)),
            Vector3.Dot(a, b)) * Mathf.Rad2Deg;
    }
}

Now, assuming you don’t have some funky namespace stuff going on, you should be able to use v.SignedAngleTo for any Vector3 v.

Hang in there. The road to enlightenment is often shrouded in clouds of confusion.

Ok found an answer on the interwebs…

float angle = Mathf.Atan2(vec2.y - vec1.y, vec2.x - vec1.x)  * 180 / Mathf.PI;

This was actually two functions that I combined into one and looks very similar to yours. I’ve reduced my code to two lines and without any additional functions. Never would have gotten there without you pointing out I need to use eulerAngles and not lookAt.

Many Thanks Joe.

2 Likes