Vector3基础和Transform位置

本文介绍了Unity游戏引擎中Transform组件的基础操作,包括Vector3的使用,如表示点和向量,以及基本运算。详细讲解了位置属性position和localPosition的区别,特别是在父对象存在时的影响。还探讨了如何正确进行位置赋值,并提供了位移计算的方法,包括手动计算和使用Unity API进行平移的操作示例。

游戏对象(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);

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值