1
\$\begingroup\$

I've attached this script to the camera and am using it to rotate the camera around an object. It's currently rotating freely but I'd like it rotate 90 degrees smoothly, over 60 frames, when the button is pressed. So that four presses of the left arrow key would have the have the camera rotate the full 360 degrees over 240 frames and back to it's starting position. I can't seem to figure out how to do this. Any help would be appreciated.

public GameObject targetObject;
public float rDistance = 1.0f;
public float rSpeed = 1.0f;;

// Update is called once per frame
void Update()
{

    // Trigger functions if Rotate is requested
    if (Input.GetKey(KeyCode.LeftArrow)) {
        RotateLeft(true);
    } else if (Input.GetKey(KeyCode.RightArrow)) {
        RotateLeft(false);
    }

}

protected void RotateLeft(bool goLeft)
{

    float step = rSpeed * Time.deltaTime;
    float orbitCircumfrance = 2F * rDistance * Mathf.PI;
    float distanceDegrees = (rSpeed / orbitCircumfrance) * 360;
    float distanceRadians = (rSpeed / orbitCircumfrance) * 2 * Mathf.PI;

    if (goLeft) {
        transform.RotateAround(targetObject.transform.position, Vector3.up, -distanceRadians);
    } else {
        transform.RotateAround(targetObject.transform.position, Vector3.up, distanceRadians);
    }

}
\$\endgroup\$
0
\$\begingroup\$

You'll want to use Lerp. Lerp interpolates between 0 and 100%, so you can use it inside the Update loop to interpolate from the angle that you are to the angle that you want to be, according with a speed and the time elapsed.

You can see the documentation of Mathf.Lerp() here, but I also recommend that you take a look in the documentation of Quaternion.Lerp() here and Quaternion.Slerp() here.

If you just google unity rotation lerp you'll find plenty of examples.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.