transform.Rotate() Function in Unity
Notes:
transform.Rotate() Function in Unity:
Rotating Game objects using transform.Rotate():
Rotating means changing orientation (or angle) of a game object
transform.Rotate():
- is used to rotate a game object relative to world (Global) or self (Local) coordinate system
Rotation in World Space or Self Space:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeController : MonoBehaviour {
// must use current rotation to set initial rotation
// instead of rotation property in the inspector
public Vector3 currentRotation;
public Vector3 anglesToRotate;
void Start () {
currentRotation = new Vector3 (currentRotation.x % 360f, currentRotation.y % 360f, currentRotation.z % 360f);
anglesToRotate = new Vector3 (anglesToRotate.x % 360f, anglesToRotate.y % 360f, anglesToRotate.z % 360f);
Quaternion rotationX = Quaternion.AngleAxis (currentRotation.x, new Vector3 (1f, 0f, 0f));
Quaternion rotationY = Quaternion.AngleAxis (currentRotation.y, new Vector3 (0f, 1f, 0f));
Quaternion rotationZ = Quaternion.AngleAxis (currentRotation.z, new Vector3 (0f, 0f, 1f));
//this.transform.rotation = rotationY * rotationX * rotationZ;
//or
this.transform.localRotation = rotationY * rotationX * rotationZ;
}
void Update () {
//this.transform.Rotate (anglesToRotate * Time.deltaTime);
//this.transform.Rotate(anglesToRotate * Time.deltaTime,Space.Self);
//this.transform.Rotate(anglesToRotate * Time.deltaTime,Space.World);
//this.transform.Rotate (new Vector3 (1f, 0f, 0f), anglesToRotate.x * Time.deltaTime);
//this.transform.Rotate (new Vector3 (0f, 1f, 0f), anglesToRotate.y * Time.deltaTime);
//this.transform.Rotate (new Vector3 (0f, 0f, 1f), anglesToRotate.z * Time.deltaTime);
//this.transform.Rotate (new Vector3 (1f, 0f, 0f), anglesToRotate.x * Time.deltaTime,Space.Self);
//this.transform.Rotate (new Vector3 (0f, 1f, 0f), anglesToRotate.y * Time.deltaTime,Space.Self);
//this.transform.Rotate (new Vector3 (0f, 0f, 1f), anglesToRotate.z * Time.deltaTime,Space.Self);
//this.transform.Rotate (new Vector3 (1f, 0f, 0f), anglesToRotate.x * Time.deltaTime,Space.World);
//this.transform.Rotate (new Vector3 (0f, 1f, 0f), anglesToRotate.y * Time.deltaTime,Space.World);
//this.transform.Rotate (new Vector3 (0f, 0f, 1f), anglesToRotate.z * Time.deltaTime,Space.World);
//this.transform.Rotate (anglesToRotate.x * Time.deltaTime, anglesToRotate.y * Time.deltaTime, anglesToRotate.z * Time.deltaTime);
this.transform.Rotate (anglesToRotate.x * Time.deltaTime, anglesToRotate.y * Time.deltaTime, anglesToRotate.z * Time.deltaTime,Space.Self);
//this.transform.Rotate (anglesToRotate.x * Time.deltaTime, anglesToRotate.y * Time.deltaTime, anglesToRotate.z * Time.deltaTime,Space.World);
currentRotation = currentRotation + anglesToRotate * Time.deltaTime;
currentRotation = new Vector3 (currentRotation.x % 360f, currentRotation.y % 360f, currentRotation.z % 360f);
}
}