Vector3.RotateTowards until object is aligned.

Hello, I want to use RotateTowards (or any other way to do this if you have a suggestion) to make my object (Obj1) face towards another that has been defined by an event (Obj2, marked as the goal when a separate collider connected to the same pivot hits it.)

When the player lets go of Obj1 I would like it to rotate towards facing Obj2, and then stop once facing it.

I’ve attempted to do angles and stuff but I just can’t get it to work properly.

public void SetLastNotch(GameObject notch)
{
    lastNotch = notch;
}

public IEnumerator NotchSnap()
{
    GameObject pivot = transform.parent.gameObject;
    Vector3 dirFromAtoB = (lastNotch.transform.position - pivot.transform.position).normalized;
    float dotProd = Vector3.Dot(dirFromAtoB, pivot.transform.up);
    print(dotProd);
    while (dotProd > 0.9)
    {
        print("rotate");
        pivot.transform.rotation = Vector3.RotateTowards(pivot,dotProd);
        yield return new WaitForSeconds(0.1f);
    }
    StopAllCoroutines();
}

This is my code so far. lastNotch is the object that was last touched by a separate hitbox.
TL;DR: Rotate “pivot” to look at lastNotch and then stop when it is aligned (within a certain tolerance i guess?)

RE-EDIT:

Sorry, I see what you mean now. I still kinda use that same method, but it uses a different check:

public void TurnTowards(Vector3 turnTo)
{
     Vector3 direction = turnTo - trans.position;
     direction.y = 0;
     int fraction = 1; // might be needed in future
     Quaternion targetRotation = Quaternion.LookRotation(direction, Vector3.up);
     desiredRotation = Mathf.RoundToInt(targetRotation.eulerAngles.y);
     currentRotation = Mathf.RoundToInt(trans.rotation.eulerAngles.y);

     if (desiredRotation < currentRotation - turnSpeed * fraction ||
           desiredRotation > currentRotation + turnSpeed * fraction) 
     {
           trans.rotation = Quaternion.RotateTowards(trans.rotation, targetRotation, turnSpeed);
     }
}

As you can see, I add an extra variable check to stop it from rotating. Making the variable of rotation into a Euler Y, as it shows in inspector, is basically degrees. Also the handling of Gimbal Lock is not needed as the rotation check from 360 to 0 works just fine :slight_smile: