In the post I will be covering a few rotation concepts used in Unity3D, these apply to development in 3D or 2D and I will be using C# as the language. Lets start with something simple:
Object Rotation
The following snippet will change an objects rotation to a specific degree. The scripts should be attached to the object that needs to be animated.
transform.Rotate(0, 0, 90);
Animated object Rotation
Adding the following snipped into an update loop will cause it to rotate anti-clockwise every frame.
void Update () { transform.Rotate(0, 0, 100*Time.deltaTime); }
lets break it down a bit. transform.Rotate(); The rotate function accepts a Vector3 as it’s parameter.
Vector3 is a representation of a point in 3D space (x,y,z). This structure is used throughout Unity to pass 3D positions and directions around. It also contains functions for doing common vector operations.
In simple terms, you can pass x, y, z into the Rotate function and it will rotate an object to that value.In the 3rd parameter I am passing in a value of 100 multiplied by Time.deltaTimeTime.deltaTime is the a value that represents how much time has passed since the last rendered frame in your game loop. Changing the value of the multiplied number will speed up or slow down the rotation
transform.Rotate(0, 0, 100*Time.deltaTime); //fast anti-clockwise rotation transform.Rotate(0, 0, 10*Time.deltaTime); // slower anti-clockwise rotation transform.Rotate(0, 0, 100* -Time.deltaTime); // fast clockwise rotation transform.Rotate(0, 0, 10* -Time.deltaTime); // slower clockwise rotation
Ok so lets try another useful rotation
Rotate sprite/object towards mouse
void Update () { Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position); }
Thankyou very much. A very brief and simple explanation.