UnityAPI之Transform
所有物体都会含有Transform组件,这句话告诉我们他是一个组件,即他继承于Component类.
这个组件负责存储和操作物体的位置,旋转和大小,这种操作是依赖于他底层的计算机图形接口的(比如Windows用户是DirectX,Mac用户是OpenGL),当然这些接口对于他们的操作大抵相同利用矩阵变换的知识,在物体本身的位置矩阵上乘以一个线性变换或者平移变换矩阵.
transform类提供一个迭代器,这使他拥有类似数组的性质(所有扩展了enumerators接口的都可以使用foreach循环)
public class ExampleClass : MonoBehaviour {
void Example() {
foreach (Transform child in transform) {
child.position += Vector3.up * 10.0F;
}
}
}
这段代码是unity帮助文档的示范代码,扩展这个接口的目的主要是因为在unity中子物体和父物体在位置和大小上有着很紧密的耦合,比如缩放:
print(transform.localscale);
print(transform.lossyscale);
localscale指的是相对于父物体的缩放比例,而lossyscale是实际缩放比例(=自身缩放比例*父物体缩放比例))
在面板上表示的是自身缩放比例,放大父物体的时候子物体也会跟着缩放.
你可以对物体执行移动操作,我们知道如果要研究物体运动一定要选定好坐标系和参考系,unity提供了两种坐标系:
世界坐标系:可以理解为空间直角坐标系,基向量对时间求导为0
自身坐标系:是一种本征坐标系,以自身建立直角坐标系,基向量对时间求导不为0
public enum Space
{
World,
Self
}
unity提供了一个枚举量,表示坐标系的类型
transform.position += new Vector3(1, 0, 0);
transform.Translate(0,0,1);
transform.Translate(0, 0, 1, Space.World);
三个参数表示沿着x移动几个单位,沿着y移动几个单位,沿着z移动几个单位,也可以用+等进行标述不过要注意描述位置和位移都是使用空间向量.
旋转:你可以提供坐标系和围绕各个轴的旋转角度来对物体机型旋转
transform.Rotate(0,10,0);
transform.Rotate(0,10,0,Space.World);
也可让物体围绕着其他物体的各个轴来进行旋转
transform.RotateAround(tf.Position,Vector3.up,30);`
transform提供了获取子物体和父物体并修改他们的属性和方法
//获取当前组件的根,即祖宗,不可改写
Transform root = this.transform.root;
transform.parent,可以改写他的父物体
Transform tf=transform.parent;
//设置父物体的方法
transform.SetParent(tf);
//世界坐标系,局部坐标系
transform.SetParent(tf,true);//使用世界坐标系
transform.SetParent(tf, false);//视为局部坐标系
transform.position += new Vector3(1, 0, 0);
//查找,只能获取子物体的内容
transform.Find("Main Camera");