Transform组件的关于旋转转向方面的API解析
发表于2017-01-02
本片文章主要讲解Transform组件的关于旋转与转向的方面的API。比如eulerAngles、localEulerAngles、rotation、localRotation、Rotate、RotateAround、LookAt。
1、eulerAngles/localEulerAngles
指使用欧拉角的方式围绕穿过游戏物体的自身位置点并且平行于游戏物体的“父级”的世界/局部坐标轴(X/Y/Z)方向的“隐形轴”旋转一定的角度。
父级Sphere的世界坐标
子级Cube的世界坐标

在Cube上挂在一个测试脚本:测试eulerAngles 的作用
1 2 3 4 5 6 7 8 | public float yRotation = 1f; void Update() { yRotation += 0.5f; transform.eulerAngles = new Vector3(0, yRotation, 45); // transform.localEulerAngles = new Vector3(0, yRotation,45); } |


父级Sphere的局部坐标

子级Cube的局部坐标

在Cube上挂在一个测试脚本:测试localEulerAngles 的作用
1 2 3 4 5 6 7 8 | public float yRotation = 1f; void Update() { yRotation += 0.5f; //transform.eulerAngles = new Vector3(0, yRotation, 45); transform.localEulerAngles = new Vector3(0, yRotation, 45); } |
运行结果如下图:


发现Cube是在围绕穿过自身位置点并且平行于Sphere的局部坐标的Y轴的“隐形轴”旋转。
注意:通过eulerAngle/localEulerAngle设置新值时,要同时设置x/y/z的值transform.localEulerAngles = newVector3(0, yRotation, 45);最好不要单个设置某个轴的值transform.localEulerAngles.y= yRotation,它很可能会产生偏移和不希望的旋转。
2、rotation/localRotation
原理与eulerAngles/licalEulerAngles类似,指使用四元组的方式围绕穿过游戏物体的自身位置点并且平行于游戏物体的“父级”的世界/局部坐标轴(X/Y/Z)方向的“隐形轴”旋转一定的角度。
在Cube上挂在一个测试脚本:测试rotation 的作用
在Cube上挂在一个测试脚本:测试rotation 的作用
1 2 3 4 5 6 7 8 9 10 11 | public Quaternion yRotation; public float y = 0; void Update() { y+=0.5f; yRotation = Quaternion.Euler(0,y,45); transform.rotation = Quaternion.Slerp(transform.rotation,yRotation, Time.deltaTime * 1); //transform.localRotation =Quaternion.Slerp(transform.localRotation, yRotation, Time.deltaTime * 1); } |


发现Cube是在围绕穿过自身位置点并且平行于Sphere的世界坐标的Y轴的“隐形轴”旋转。
在Cube上挂在一个测试脚本:测试localRotation的作用
测试代码如下:
1 2 3 4 5 6 7 8 9 10 11 | public Quaternion yRotation; public float y = 0; void Update() { y+=0.5f; yRotation = Quaternion.Euler(0,y,45); //transform.rotation = Quaternion.Slerp(transform.rotation,yRotation, Time.deltaTime * 1); transform.localRotation = Quaternion.Slerp(transform.localRotation,yRotation, Time.deltaTime * 1); } |


发现Cube是在围绕穿过自身位置点并且平行于Sphere的局部坐标的Y轴的“隐形轴”旋转。
3、Rotate
原理似乎与上面2种不一样。游戏物体围绕自身的世界/局部坐标(X/Y/Z)轴旋转一定的角度。
测试代码如下:
测试代码如下:
1 2 3 4 5 | void Update() { transform.Rotate(Vector3.up, Time.deltaTime*10f, Space.World); //transform.Rotate(Vector3.up,Time.deltaTime*10f,Space.Self); } |

1 2 3 4 5 | void Update() { //transform.Rotate(Vector3.up, Time.deltaTime * 10f,Space.World); transform.Rotate(Vector3.up,Time.deltaTime*10f,Space.Self); } |

发现Cube在围绕自身的局部坐标Y轴旋转。
4、RotateAround
让游戏物体围绕世界坐标系中某一位置的某一轴旋转。有点儿类似地球围绕太阳公转一样。
测试代码如下:
测试代码如下:
1 2 3 4 | void Update() { transform.RotateAround(Vector3.zero, Vector3.up, 20 * Time.deltaTime); } |


通俗地讲,就是凝视着“目标位置”。凝视对象的局部坐标的Z轴指向被凝视对象的position,并且凝视对象的局部坐标的Y轴与被凝视对象局部坐标的Y轴“同向平行”。
测试代码如下:
1 2 3 4 | void Start() { transform.LookAt(target.position); } |

运行代码,两者之间的位置关系如下
