0
\$\begingroup\$
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);
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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:

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .