Vector3 vectmp = vec.normalized;
vectmp为vec的单位向量。vec.normalized():返回vec的单位向量
向量相减
打开unity项目,新建一个cube,为了方便查看可以缩小一点。给cube新建一个脚本,脚本代码如下:
public class VectorDemo : MonoBehaviour
{
// Update is called once per frame
void Update()
{
Demo01();
}
private void Demo01()
{
Vector3 pos = this.transform.position;
//画出物体位置所对应的的向量
Debug.DrawLine(Vector3.zero, pos);
//画出物体位置所对应的单位向量,用红线表示
Debug.DrawLine(Vector3.zero, pos.normalized,Color.red);
print(pos.magnitude); //输出向量模长
}
}
运行效果
复制之前的cube,并给它附上画出相减向量的relDemo脚本,脚本代码如下:
public class VectorRelDemo : MonoBehaviour
{
public GameObject cube; //在组件面板中把另一个cube拖入这个变量
// Update is called once per frame
void Update()
{
Demo();
}
private void Demo()
{
Vector3 relativeDirection = cube.GetComponent<Transform>().position - this.GetComponent<Transform>().position;
Debug.DrawLine(Vector3.zero,relativeDirection,Color.green);
}
}
运行效果
实现当按下A键后在物体B的坐标生成一个物体C,物体C从物体B向物体A的方向径直移动。 在上面实例的基础上,先创建一个按A生成物体C的脚本FireDemo,并赋给物体B,脚本代码如下:
public class FireDemo : MonoBehaviour
{
public GameObject bullet;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
CreateBullet();
}
}
private void CreateBullet()
{
bullet = GameObject.CreatePrimitive(PrimitiveType.Sphere);
bullet.transform.parent = this.transform; //作为物体B的子物体
bullet.AddComponent(System.Type.GetType("Bullet")); //添加脚本Bullet
bullet.transform.position = this.transform.position;
}
}
需要让物体C从B移动到A,只需要用从原点指向C的向量加上从B指向A的向量(上面的向量相减所求得的向量),为了能看到移动过程,可以缩短b->A的向量,脚本代码如下:
public class Bullet : MonoBehaviour
{
private Vector3 move;
// Start is called before the first frame update
void Start()
{
move = this.GetComponentInParent<VectorRelDemo>().relativeDirection;
}
// Update is called once per frame
void Update()
{
//为了确保移动速度不与两物体间距(向量模长)相关,需要
//先把移动向量变为单位向量,再根据后面的参数自定义速度。
this.transform.Translate(move.normalized*0.05f);
}
}
运行效果