Unity学习记录-Vector和Transform

常用的Vector向量

1
print(Vector3.zero);
  • 0,0,0
1
print(Vector3.right);
  • 1,0,0
1
print(Vector3.left);
  • -1,0,0
1
print(Vector3.forward);
  • 0,0,1
1
print(Vector3.back);
  • 0,0,-1
1
print(Vector3.up);
  • 0,1,0
1
print(Vector3.down);
  • 0,-1,0

Vector常用方法

  • 计算两点之间的距离
1
2
3
Vector3 v1 = new Vector3(1, 1, 0);
Vector3 v2 = new Vector3(0, 0, 1);
Vector3.Distance(v1, v2);//返回一个float

Transform位置相关

  • 相对于世界坐标系位置
1
print(this.transform.position);
  • 相对于父对象的位置
1
print(this.transform.localPosition);
  • 对象当前的面朝向(建立模型时,以Z轴为前方建模)
1
print(this.transform.forward);
  • 对象当前的头顶朝向
1
print(this.transform.up);
  • 对象当前的右手边朝向
1
print(this.transform.right);

位移和旋转的计算

位移的计算

  • 方向 X 速度 X 时间
  1. 自己计算

    1
    2
    float speed = 1f;
    this.transform.position += this.transform.forward * speed * Time.deltaTime;
  2. 利用API计算

    • 参数一:表示位移速度
    • 参数二:表示位移的相对坐标系,默认为自身坐标系
    1
    2
    3
    4
    5
    this.transform.Translate(Vector3.forward * speed * Time.deltaTime,Space.World);//相对于世界坐标,往001动

    this.transform.Translate(this.transform.forward * speed * Time.deltaTime, Space.World);//相对于世界坐标,往自己的面朝向动

    this.transform.Translate(Vector3.forward*speed*Time.deltaTime, Space.Self);//相对于自身坐标系,往001动

    注意:不要这样写:

    1
    2
    this.transform.Translate(this.transform.forward * speed * Time.deltaTime, Space.Self);
    //这样是以相对自身的坐标系,朝自身前方朝向的方向(相对于世界)移动,会出现向量叠加

旋转的计算

自转

  • 第一个参数:旋转的速度
  • 第二个参数:相对的坐标系
1
this.transform.Rotate(new Vector3(0, 10, 0) * Time.deltaTime, Space.Self);//绕自己的y轴自转

公转

  • 第一个参数:相对于哪个点公转
  • 第二个参数:相对于哪一个轴公转
  • 第三个参数:速度
1
this.transform.RotateAround(Vector3.zero, Vector3.up, 10 * Time.deltaTime);

绕 0,1,0 公转

示例代码:模拟地球运动

1
2
3
4
5
void Update()
{
this.transform.Rotate(new Vector3(0, 10, 0) * Time.deltaTime, Space.Self);//绕自己的y轴旋转
this.transform.RotateAround(Vector3.zero, new Vector3(0,1,-1), 10 * Time.deltaTime);//绕0,1,0公转
}

效果: