Calculate Angle Between Vectors on a Single Plane - Unity3D

 I wanted to follow an object on a single plane while using 3D and nested game objects. This proved tricky when the orientation of the parents is constantly moving. 

Finally I found the answer here:
https://forum.unity.com/threads/is-vector3-signedangle-working-as-intended.694105/

So, well done lordofduct


Here is my code:

public Transform ObjectToFollow;

void Update()
{
// move towards the object.
    transform.position = Vector3.MoveTowards(transform.position, ObjectToFollow.position, Speed * Time.deltaTime);
// find directions in local space.
    var targetDirection = transform.InverseTransformDirection(ObjectToFollow.position - transform.position);
    var forward = transform.InverseTransformDirection(transform.forward);
    var angle = AngleAroundAxis(targetDirection, forward, transform.InverseTransformDirection(transform.up));

    // rotate towards the object to follow
    transform.Rotate(new Vector3(0, angle, 0), Space.Self);
}

 

// Calculates the angle between vectors as if projected on a plane.
public static float AngleAroundAxis(Vector3 v, Vector3 forward, Vector3 perpenducularAxis, bool clockwise = false)
{
    Vector3 right;
    if (clockwise)
    {
        right = Vector3.Cross(forward, perpenducularAxis);
        forward = Vector3.Cross(perpenducularAxis, right);
    }
    else
    {
        right = Vector3.Cross(perpenducularAxis, forward);
        forward = Vector3.Cross(right, perpenducularAxis);
    }
    return Mathf.Atan2(Vector3.Dot(v, right), Vector3.Dot(v, forward)) * Mathf.Rad2Deg;
}


Comments