Unity Vector3类的介绍(反射,投影,垂直向量,夹角)

本文深入探讨Unity中Vector3类的高级应用,包括计算向量夹角、模长平方、向量投影、规范化及垂直向量计算、反射向量等。通过具体代码示例,展示了如何在游戏开发中高效利用这些数学工具。

1. Angle :计算两个向量的夹角

Vector3.Angle(trans1.position,trans2.position);

2. SqrMagnitude:  向量的模长平方,比较向量的长度的大小时比magnitude更省性能,因为少个内部开方。

3. ClampMagnitude: 返回向量,长度不会大于设定的length,如果原向量模长小于length,返回向量不变化,但是如果模长大于length,返回向量模长限制为length。

  Vector3.ClampMagnitude(target,length);

4. OrthoNormalize:使向量规范化,并且返回该向量在三维空间的两个垂直向量

Vector3.OrthoNormalize( ref normal, ref  tangent, ref binormal);

 ref是代表把向量标准化。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestVector : MonoBehaviour
{
    public Transform t1;
    private Vector3 tangent;
    private Vector3 binNormal;
    private void Update()
    {
        Vector3 norm = t1.position;
        //计算norm的两个垂直向量
        Vector3.OrthoNormalize(ref norm, ref tangent, ref binNormal);

        Debug.DrawLine(Vector3.zero, norm);
        Debug.DrawLine(Vector3.zero, tangent, Color.red);
        Debug.DrawLine(Vector3.zero, binNormal, Color.green);

     
    }
}

运行结果如下: 

5. Vector3.ProjectOnPlane  向量投影:投影向量到一个平面上由垂直到该平面的法线定义

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestVector : MonoBehaviour
{
    public Transform t1;
 
    private void Update()
    {
        Vector3 norm = t1.position;
        //计算t1物体在地面上的投影project
        Vector3 project = Vector3.ProjectOnPlane(norm, Vector3.up);
        Debug.DrawLine(Vector3.zero, norm);
        Debug.DrawLine(Vector3.zero, project, Color.red);//投影线

      

    }
}

6. Vector3.Reflect 沿着法线反射向量,类似于物理的入射光、反射光

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestVector : MonoBehaviour
{
    public Transform t1;
 
    private void Update()
    {
        Vector3 norm = t1.position;
        //计算norm的反射向量reflect
        Vector3 reflect = Vector3.Reflect(norm, new Vector3(0,1,0));
        Debug.DrawLine(Vector3.zero, norm);
        Debug.DrawLine(Vector3.zero, new Vector3(0,1, 0), Color.yellow);
        Debug.DrawLine(Vector3.zero, reflect, Color.red);//反射向量
    }
}

 

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋斗的菇凉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值