Unity把余弦值转成弧度和角度

 Unity 中通过向量点成可以计算出cos<夹角>=DOT(A,B);

但是Mathf.Acos(点乘后的结果) 得出的是把余弦值转换成弧度

我们需要除以Mathf.Deg2Rad 才可以转换成角度!

//拿到一个物体的前方向量

Vector3 RoleForwardV = MainRole.transform.forward;

//计算另一个物体与当前物体连线方向向量

Vector3 RoleToMonsterV = Monster.transform.position - MainRole.transform.position;

//点乘两个单位向量

float DotResult = Vector3.Dot(RoleForwardV, RoleToMonsterV.normalized);
float Jiaodu = Mathf.Acos(DotResult ) / Mathf.Deg2Rad;//这是两个向量夹角角度


Mathf.Acos(DotResult); //--它计算余弦值对应的弧度

Mathf.Acos(DotResult)/Mathf.Rad2Deg; //--它计算余弦值对应的角度

赠送一个完整的点乘、叉乘代码示例:

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

public class vEC : MonoBehaviour
{
    public GameObject ONECUBE;
    public GameObject onesphere;


    // Dot 需要一个物体前方向量  连线向量

    void Update()
    {
        Vector3 oneFront = ONECUBE.transform.forward;//拿到物体前方向量
        Vector3 cubeTosphere =(ONECUBE.transform.position - onesphere.transform.position).normalized;
        Debug.Log(cubeTosphere.magnitude);//(2,1,2)
       float dotresult= Vector3.Dot(oneFront, cubeTosphere);
        //cos(a)=dotresult
        if (dotresult>0)
        {
            Debug.Log("0-90 前方");

            //onesphere.transform.Translate(cubeTosphere*10f*Time.deltaTime);
        }


        float Jiaodu = Mathf.Acos(dotresult) / Mathf.Deg2Rad;//这是两个向量夹角角度
      
        Debug.Log("两个向量的夹角是"+Mathf.Acos(dotresult)/Mathf.Deg2Rad+"度");


        Debug.DrawRay(ONECUBE.transform.position,ONECUBE.transform.forward*100f);
        Debug.DrawRay(ONECUBE.transform.position, cubeTosphere * 100f);

        Vector3 oneCross = Vector3.Cross(oneFront, cubeTosphere);//向量叉乘X
        Debug.DrawRay(oneFront, oneCross*100,Color.red);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Unity3d青子

难题的解决使成本节约,求打赏

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

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

打赏作者

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

抵扣说明:

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

余额充值