Unity vector3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Vector3_Class : MonoBehaviour { // 本脚本用于演示向量Vector3类的变量和方法 Vector3 OneVect; Vector3 ForwardZVect; Vector3 SecondVectorPoint;// 用于存放坐标点 Vector3 ThirdVectorPoint;// 用于存放坐标点 public GameObject OneCube;// 用于存放 一个目标物体 float Speed = 20f; void Start () { #region OneVect = new Vector3(0, 0, 10);//实例化一个三维向量类对象 ,使用其点功能 ForwardZVect = new Vector3(0,0,200); SecondVectorPoint = new Vector3(1, 1, 1); ThirdVectorPoint = new Vector3(10,15,20); ThirdVectorPoint.Normalize(); Debug.Log("把向量Nor归一化的结果:"+ThirdVectorPoint); #endregion //获得或者赋值向量的三个分量 Vector3 Onepoint = new Vector3(0,20,30); //实例化 创建 一个向量 用作点坐标 Onepoint.x = 10f; // 人为改变X坐标数值 Debug.Log("向量Onepoint的分量:X: "+ Onepoint.x+"Y: "+Onepoint.y+"Z: "+ Onepoint.z); //获得或者赋值向量的三个分量 #region 向量长度和归一化属性讲解 //获取向量的长度、单位化值、获取向量分量x,y,z Debug.Log(OneVect.magnitude+ " 获取OneVect向量的长度"); //获取OneVect向量的长度 Debug.Log(ForwardZVect.magnitude+ "获取ForwardZVect向量的【长度】"); //获取ForwardZVect向量的【长度】 Debug.Log(SecondVectorPoint.magnitude+" 该数值 是 向量 (1,1,1)的长度,1.73也就是根号3"); //获取SecondVectorPoint向量的长度=【根号3】 Debug.Log(ThirdVectorPoint.magnitude+"第三个向量长度"); Debug.Log("把向量归一化的结果:"+ThirdVectorPoint.normalized); //获取ThirdVectorPoint向量的归一化值,单位向量,方向不变,长度为1 Debug.Log(ThirdVectorPoint.normalized.magnitude); #endregion } // Update is called once per frame void Update () { DirMove();//使用Vector3的静态变量,使用其向量的作为一个【方向】属性 PointMove();此时向量作为世界坐标系 的一个【坐标点】 Debug.DrawLine(Vector3.zero, ThirdVectorPoint, Color.blue);//测试单位向量 Debug.DrawLine(Vector3.zero, ThirdVectorPoint.normalized, Color.green); Debug.DrawLine(OneVect, ForwardZVect, Color.red);//向量起点到向量终点 绘制一条射线 Debug.DrawLine(OneVect, OneCube.transform.position, Color.yellow);//向量起点到向量终点 绘制一条射线 } private void DirMove()//使用Vector3的静态变量,使用其向量的方向属性 { //Vector3的静态变量方向点 if (Input.GetKeyDown(KeyCode.W)) { OneCube.transform.Translate(Vector3.forward * Speed);//向前移动 Translate默认是自身坐标系 } if (Input.GetKeyDown(KeyCode.S)) { OneCube.transform.Translate(Vector3.back * Speed);//向前移动 } if (Input.GetKeyDown(KeyCode.A)) { OneCube.transform.Translate(Vector3.left * Speed);//向前移动 } if (Input.GetKeyDown(KeyCode.D)) { OneCube.transform.Translate(Vector3.right * Speed);//向前移动 } if (Input.GetKeyDown(KeyCode.Alpha1)) { OneCube.transform.Translate(Vector3.up * Speed);//向前移动 } if (Input.GetKeyDown(KeyCode.Alpha2)) { OneCube.transform.Translate(Vector3.down * Speed);//向前移动 } } private void PointMove()//演示向量 作为一个坐标点的使用 { //此时向量作为世界坐标系 的一个坐标点 if (Input.GetKeyDown(KeyCode.O)) { OneCube.transform.position = OneVect; } if (Input.GetKeyDown(KeyCode.P)) { OneCube.transform.position = ForwardZVect; } } }