赞
踩
讲讲Unity中的向量有关知识,一些概念在初高中就学过,就不解释了。向量只能与自己相同维度进行计算,二维向量只能与二维向量运算,三维同理
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Vector : MonoBehaviour { // Start is called before the first frame update void Start() { Vector3 v1 = new Vector3(1, 1, 1); Vector3 v2 = new Vector3(2, 2, 2); Debug.Log(v1 + v2); Debug.Log(v2 + v1); } // Update is called once per frame void Update() { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Vector : MonoBehaviour { // Start is called before the first frame update void Start() { Vector3 v1 = new Vector3(1, 1, 1); Vector3 v2 = new Vector3(2, 2, 2); Debug.Log(v1 - v2); Debug.Log(v2 - v1); } // Update is called once per frame void Update() { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Vector : MonoBehaviour { // Start is called before the first frame update void Start() { Vector3 v1 = new Vector3(1, 1, 1); Vector3 v2 = new Vector3(2, 2, 2); Debug.Log(3 * v1); Debug.Log(v2 / 2); } // Update is called once per frame void Update() { } }
向量点乘可以判断出目标物体在我的前方还是后方。大于零在前方,小于零在后方。
意义:点乘描述了2个方向的相似程度
代码示例
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Vector : MonoBehaviour { // Start is called before the first frame update void Start() { Vector3 v1 = new Vector3(1, 1, 1); Vector3 v2 = new Vector3(2, 2, 2); Debug.Log(Vector3.Dot(v1, v2)); Debug.Log(Vector3.Dot(v2, v1)); } // Update is called once per frame void Update() { } }
向量叉乘可以判断出目标物体在我的左边还是右边。大于零在右方,小于零在左方。
意义:叉乘得到垂直于这2个的向量的一个向量
代码示例
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Vector : MonoBehaviour { // Start is called before the first frame update void Start() { Vector3 v1 = new Vector3(1, 1, 1); Vector3 v2 = new Vector3(2, 2, 2); Debug.Log(Vector3.Cross(v1, v2)); Debug.Log(Vector3.Cross(v2, v1)); } // Update is called once per frame void Update() { } }
讲到这个向量归一化
之前,补充一个概念,单位向量也叫做标准化向量,就是大小为1的向量。
对任意的非零向量,我们都可以计算出它的单位向量,即将其归一化(normalization)。
向量的归一化:求得向量的长度后,用向量除以它的长度。
意义:在一些方向,角度求解中应用,只关心相互间的方位,不考虑长度
代码示例
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Vector : MonoBehaviour { // Start is called before the first frame update void Start() { Vector3 v1 = new Vector3(1, 1, 1); Vector3 v2 = new Vector3(2, 2, 2); Debug.Log(v1.normalized); Debug.Log(v1); Debug.Log(v2.normalized); Debug.Log(v2); v1.Normalize(); Debug.Log(v1); v2.Normalize(); Debug.Log(v2); } // Update is called once per frame void Update() { } }
Vector3.normalized
是一个属性,当前向量保持不变,返回一个新的归一化向量。Vector3.Normalize
是一个方法,此函数将更改当前向量。日常使用中最多的还是 点乘 与 叉乘
简单的说,点乘判断角度,叉乘判断方向。当一个敌人在你身后的时候,叉乘可以判断你是往左转还是往右转更好的转向敌人,点乘得到你当前的面朝向的方向和你到敌人的方向的所成的角度大小。
enjoy ~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。