thelearnerofcode
thelearnerofcode

Reputation: 346

How do I smoothly rotate the camera in unity?

I am making a 2d unity 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 run the game, it gives me an error. Anybody have tips on how I can (smoothly) rotate the camera from side to side?

Upvotes: 4

Views: 30344

Answers (4)

Maaz Irfan
Maaz Irfan

Reputation: 81

Easiest way is to place that code into your gameobject add current camera which you want it to rotate.

public class swipebutton : MonoBehaviour

{ public Camera cam;

void Update()
{

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

}

Upvotes: 1

maraaaaaaaa
maraaaaaaaa

Reputation: 8163

The error is because you are missing the new initializer.

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

Upvotes: 1

maZZZu
maZZZu

Reputation: 3615

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

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

And attaching script component containing it to the camera. But then it is rotating randomly all the time.

I'm not sure, from the question, what kind rotation do you want. But you can use for example this

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

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

Upvotes: 7

Daniel Samson
Daniel Samson

Reputation: 718

Don't use Camera.main. Write a class for your camera and then add it to the camera in the scene. 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

Upvotes: 3

Related Questions