C#中点乘和叉乘如何辨别角度方位

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

public class DotAndCross : MonoBehaviour {
    public Transform a;
    public Transform b;
    // Update is called once per frame
    void Update () {

        GetAngle( a.position,  b.position);
    }
    //点积,点乘
    public void  TestDot(Vector3 a, Vector3 b)
    {
        //a·b=|a|·|b|cos<a,b>  点乘求角度 ,叉乘求方向    
        //<a,b>= arccos(a·b / (|a|·|b|))    arccos 反余弦 (点向乘/1)
        //根据点乘的正负值,得到夹角大小范围,>0,则夹角(0,90)<0,则夹角(90,180),可以利用这点判断一个多边形是面向摄像机还是背向摄像机。
        float result = Vector3.Dot(a.normalized, b.normalized);
        float radius = Mathf.Acos(result) * Mathf.Rad2Deg;
        print("result :" + result);
        print("radius :" + radius);
    }
    //叉乘
    public void TestCross(Vector3 a, Vector3 b)
    {
        //计算向量 a、b 的叉积,结果为 向量 
        //模长|c| = |a||b| sin<a,b>     <a,b> 角度 = Asin( |c| /|a||b|)
        Vector3 c = Vector3.Cross(a.normalized ,b.normalized);
        float d = Vector3.Distance(Vector3.zero,c);
        float radius = Mathf.Asin(d)*Mathf.Rad2Deg;
        print("radius :" + radius);
        print(c.y);
        if (c.y >0)
        {
            print("b在a的左边");
        }
        if (c.y < 0)
        {
            print("b在a的右边");
        }
        if (c.y == 0)
        {
            print("a和b平行");
        }

    }
    // 获取两个向量的夹角  Vector3.Angle 只能返回 [0, 180] 的值
    // 如真实情况下向量 a 到 b 的夹角(80 度)则 b 到 a 的夹角是(-80)
    // 通过 Dot、Cross 结合获取到 a 到 b, b 到 a 的不同夹角
    public void GetAngle(Vector3 a, Vector3 b)
    {
        Vector3 c = Vector3.Cross(a, b);
        float angle = Vector3.Angle(a, b);
        print(c.normalized);
        print(Vector3.Cross(a.normalized, b.normalized));
        print(Vector3.Dot(c.normalized, Vector3.Cross(a.normalized, b.normalized)));
        // b 到 a 的夹角      Mathf.Sign (f) 当 f 为正或为0 返回1,为负返回-1。
        float sign = Mathf.Sign(Vector3.Dot(c.normalized, Vector3.Cross(a.normalized, b.normalized)));
        float signed_angle = angle * sign;

        Debug.Log("b -> a :" + signed_angle);

        // a 到 b 的夹角
        sign = Mathf.Sign(Vector3.Dot(c.normalized, Vector3.Cross(b.normalized, a.normalized)));
        signed_angle = angle * sign;

        Debug.Log("a -> b :" + signed_angle);
    }
}

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值