0
private Update()
{
    // Here the transform player should rotate facing the opposite direction.
    // Determine which direction to rotate towards
    Vector3 targetDirection = targetToRotateTo.position - transform.position;

    // The step size is equal to speed times frame time.
    float singleStep = rotationSpeed * Time.deltaTime;

    // Rotate the forward vector towards the target direction by one step
    Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f);

    // Draw a ray pointing at our target in
    Debug.DrawRay(transform.position, newDirection, Color.red);

    // Calculate a rotation a step closer to the target and applies rotation to this object
    transform.rotation = Quaternion.LookRotation(newDirection);
}
DMGregory
  • 134,153
  • 22
  • 242
  • 357
Daniel Lip
  • 1,747
  • 3
  • 34
  • 75

1 Answers1

1

If your object always remains upright (green vector always points up), then this is as simple as zeroing out the y component of your target direction.

Vector3 targetDirection = targetToRotateTo.position - transform.position;
targetDirection.y = 0f;

if (targetDirection != Vector3.zero) { float singleStep = rotationSpeed * Time.deltaTime;

transform.rotation = Quaternion.RotateTowards(
                        transform.rotation,
                        Quaternion.LookRotation(targetDirection),
                        singleStep);

}

If your vertical axis might point in an arbitrary direction, then you can use the trick I've explained a few times in past Q&A:

DMGregory
  • 134,153
  • 22
  • 242
  • 357