unity-向量的加减
向量标准化(归一化)向量标准化,就是向量除以本身的模长。
using UnityEngine;using System.Collections;public class VectorDemo : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { drawMagnitude ();//test vector normalized } private void drawMagnitude(){ Vector3 pos = this.transform.position; Debug.DrawLine (Vector3.zero,pos); //both ok Vector3 nor1 = pos / pos.magnitude; Vector3 nor2 = pos.normalized; Debug.DrawLine (Vector3.zero,nor2,Color.red); }}
1.png
向量减法
向量的减法,可以用来计算两点之间的距离和相对方向。
注意减法的方向,a-b表示指向a。
using UnityEngine;using System.Collections;public class VectorDemo1 : MonoBehaviour { public Transform tr1,tr2; // Use this for initialization void Start () { } // Update is called once per frame void Update () { minusVector (); } private void minusVector(){ Vector3 relativeDirection = tr1.position - tr2.position;//world Debug.DrawLine (Vector3.zero,relativeDirection); }}
2.png
向量减法的结果,是相对于世界坐标的原点。
向量加法
可以表示物体的移动。
我们通过向量减法,可以获取到物体移动的方向。如果让某物体沿着这个方向移动,可以加上标准化向量即可。
using UnityEngine;using System.Collections;public class VectorDemo1 : MonoBehaviour { public Transform tr1,tr2; // Use this for initialization void Start () { } // Update is called once per frame void Update () { move (); } private void move(){ Vector3 relativeDirection = tr1.position - tr2.position;//world Vector3 movePos = tr2.position + relativeDirection.normalized; if (Input.GetKey (KeyCode.A)) { tr2.position = movePos; } }}
66.gif
unity给我们封装了Translate函数,可以直接调用。
using UnityEngine;using System.Collections;public class VectorDemo1 : MonoBehaviour { public Transform tr1,tr2,tr3; // Use this for initialization void Start () { } // Update is called once per frame void Update () { move (); } private void move(){ Vector3 relativeDirection = tr1.position - tr2.position;//world if (Input.GetKey (KeyCode.A)) { tr3.Translate(relativeDirection.normalized); } }}
3.gif
页:
[1]