Rotate set angle over time

Hi,

I am writing a script to rotate a cylinder and I only want it to turn a set angle then stop. I used the following but it seems to stop at the same point no matter what angle I choose. I tried using Quaternion but I could not get it to rotate the right way around.

Euler approach

using UnityEngine;
using System.Collections;

public class rotateCylinder : MonoBehaviour {

    public float totalRotation = 0;
    public float rotationAmount = 270f;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Mathf.Abs (transform.localRotation.eulerAngles.x) <= rotationAmount) {
            Debug.Log (transform.localRotation.eulerAngles.x);
            transform.Rotate (0, -Time.deltaTime * 20, 0);
        }
    }

}

Quaternion.

public float totalRotation = 0;
public float rotationAmount = 20f;

if(Mathf.Abs (totalRotation) < Mathf.Abs (rotationAmount)){
    float currentAngle = cube.transform.rotation.eulerAngles.z;
    cube.transform.rotation = Quaternion.AngleAxis(currentAngle + (Time.deltaTime * 5), Vector3.forward);
    totalRotation += Time.deltaTime * 5;
}

You might try using Quaternion.Euler instead if you’re rotating around a central axis. I find it’s a lot easier to use and visualize.

Hi and thanks for the quick reply. You mean like this? I gave this a go but it rotates the cylinder first and then rotates it. The result is the cylinder is rotating on the y axis but is no longer horizontal.

        if(Mathf.Abs (totalRotation) < Mathf.Abs (rotationAmount)){
            float currentAngle = transform.rotation.eulerAngles.x;
            transform.rotation = Quaternion.Euler(0,currentAngle + (Time.deltaTime * 5), 0);
            totalRotation += Time.deltaTime * 5;
        }

I think the problem you’re running into is that Quaternion.Euler returns a Quaternion rotation based on the Euler angles you put in. So if you want to modify the rotation from what it is currently you need to multiply the Quaternions (adding rotations) by doing

transform.rotation *= Quaternion.Euler(0, Time.deltaTime * 5f, 0);

Maybe you want to use Transform.Rotate, the version which take an axis of rotation and an angle.