Unity 通过向量点乘叉乘判断方位 |
您所在的位置:网站首页 › unity向量计算 › Unity 通过向量点乘叉乘判断方位 |
点积的计算方式为:a*b = |a| * |b| cos 其中|a|和|b|表示向量的模,表示两个向量的夹角。通过点积可以判断一个物体在另一个物体的前方还是后方。 using UnityEngine; public class Foo : MonoBehaviour { //创建两个物体A和B public Transform A; public Transform B; //点积结果 private float dot; private void Update() { Vector3 direction = B.position - A.position; dot = Vector3.Dot(direction.normalized, A.forward); } private void OnGUI() { //点积结果大于0表示物体B在物体A的前方 否则在后方 GUILayout.Label($"B在A的{(dot > 0 ? "前方" : "后方")}", "Box"); } }叉积的性质: 1.c垂直于a,c垂直于b,即向量c垂直于向量a、b所在的平面 2.模长|c| = |a| * |b| sin 3.满足右手法则。a * b != b * a 而 a * b = - b * a 可以使用叉积来判断一个物体在另一个物体的左方还是右方。 using UnityEngine; public class Foo : MonoBehaviour { public Transform A; public Transform B; private Vector3 cross; private void Update() { Vector3 direction = B.position - A.position; cross = Vector3.Cross(direction.normalized, A.forward); } private void OnGUI() { GUILayout.Label($"B在A的{(cross.y > 0 ? "左方" : "右方")}", "Box"); } } |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |