How to smoothly rotate the camera in unity?

I am making a 2d game with C #. Right now, I am trying to make the camera rotate and I am using this code:

rotateX = Random.Range (0, 50);
Camera.main.transform.eulerAngles = Vector3(0,0,rotateX);

      

But every time I try to start the game it gives me an error. Does anyone have any hints on how I can (smoothly) rotate the camera from side to side?

+3


source to share


4 answers


You can get rid of the errors by changing your code to this:

void Update () {
    float rotateX = Random.Range (0, 50);
    transform.eulerAngles = new Vector3(0,0,rotateX);
}

      

And add a script component containing it to the camera. But then it spins randomly all the time.



I'm not sure as of the question what kind of rotation you want. But you can use for example this

void Update () {
    transform.Rotate(Vector3.forward, 10.0f * Time.deltaTime);
}

      

to smoothly rotate the camera. Just change the first parameter to the axis around what you want to rotate.

+5


source


Don't use Camera.main. Write a class for your camera and then add it to the camera on stage. Use transform.rotation like this:

void Update () 
{
    transform.rotation = Quaternion.Euler(y, x, z);
    transform.position = Quaternion.Euler(y, x, z);
}

      



see this for more info: http://wiki.unity3d.com/index.php?title=MouseOrbitImproved

+3


source


The easiest way is to put this code in your game object to add the current camera you want to rotate.

public class swipebutton : MonoBehaviour

      

{public camera camera;

void Update()
{

    cam.transform.Rotate(Vector3.up, 20.0f * Time.deltaTime);
}

      

}

+1


source


The error is due to the fact that you are missing an initializer new

.

rotateX = Random.Range (0, 50);
Camera.main.transform.eulerAngles = new Vector3(0,0,rotateX); //<--- put 'new' before 'Vector3'

      

0


source







All Articles