游戏对象(GameObject)位移、旋转、缩放、父子关系、坐标转换等相关操作都由Transform处理
1、Vector3基础
Vector3主要用来表示三维坐标系中的一个点或者一个向量
// 声明: (1)Vector3 v = new Vector3(); (2)只传xy,默认z是0 Vector3 v = new Vector3(x,y) (3)Vector3 v = new Vector3(x,y,z)
// Vector3的基本运算:四则运算
// 常用(世界坐标的朝向)
Vector3.zero (0,0,0) Vector3.right (1,0,0) Vector3.left (-1,0,0) Vector3.forward (0,0,1) Vector3.back (0,0,-1) Vector3.up (0,1,0) Vector3.down (0,-1,0) // 常用的一个方法,计算两个点之间的距离
Vector3.Distance(v1,v2)
2、位置
// 相对世界坐标系,不会受父子关系的影响
this.(gameObject.)transform.position
// 相对父对象的坐标系,即一定与Inspector面板上的数值相同
// 如果想以面板坐标为准进行位置设置,则通过该坐标系修改
this.transform.localPosition
当(1)父对象的坐标为原点(0,0,0)或者(2)对象没有父对象的时候,position与localPosition的数值是一样的
// 注意:位置的赋值不能直接改变x,y,z,只能整体改变,即以下方式不支持
this.transform.position.x = 5
必须
this.transform.position.x = new Vector3(5,0,0)
// 如果只想改一个值,x,y,z要保持原有坐标一致
(1)直接复制
this.transform.position = new Vector3(5, this.transform.position.y,this.transform.position.z)
(2)先取出来,在赋值
// transform的x,y,z不能直接修改,但是Vector3可以
Vector3 vPos = this.transform.localPosition; vPos.x = 5; this.transform.localPosition; = vPos;
// 对象当前的各朝向
this.transform.forward/back/up/down/left/right
3、位移
// 理解坐标系下的位移计算公式
// 路程 = 方向 * 速度 * 时间,在Update函数中更新,方向要分清Vector3. 与 this.transform. 的区别
// 方式一: 自己计算
// 想要变化的就是position
// 用当前的位置+移动的距离,得到最终所在的位置
this.transform.position += this.transform.forward * speed * Time.deltaTime;
//方式二:API(一般使用API进行位移)
// 参数一:表示 位移多少
// 参数二:表示 相对坐标系,默认该参数是相对于自己坐标系(Space.Self)
this.transform.Translate(Vector3.forward * speed * Time.deltaTime);
等效于
this.transform.Translate(this.transform.forward * speed * Time.deltaTime, Space.World);
// 相对于世界坐标系的方向移动
this.transform.Translate(Vector3.forward * speed * Time.deltaTime, Space.World);
// 相对于自己的坐标系下的 自己的方向向量移动(实际不会让物体这样移动,实际方向相对于世界坐标会有两次偏移计算)
this.transform.Translate(this.transform.forward * speed * Time.deltaTime, Space.Self);