Unity 实现两个向量夹角为0~360度

Unity 实现两个向量夹角为0~360度实现向量夹角为 0 360

直接上代码,解释在代码注释中。

using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class Angle2PI: MonoBehaviour { 
    public Transform center; public Transform arrow; public Transform sphere; public TextMesh _piAngleText; public TextMesh _2piAngleText; public float radius = 5f; void LateUpdate() { 
    ShowAngle(); } private void ShowAngle() { 
    //向量  Vector3 center2camera = Camera.main.transform.position - center.position; //Angle接口只得到两个向量的最小夹角,不大于90度,反应的效果为两个“线”的最小夹角 float angle = Vector3.Angle(center2camera, center.right); _piAngleText.text ="Angel: "+ angle.ToString(); //叉积结果为法向量 法向量的模长=两个向量的模长相乘*正弦 Vector3 nordir = Vector3.Cross(center2camera, center.right); //获取dot值,因为夹角角度为180度或0度,仅两个值,可用于判断正负 float dot = Vector3.Dot(nordir,Vector3.down); Debug.DrawLine(Vector3.zero, nordir, Color.red); Debug.DrawLine(Camera.main.transform.position, center.position, Color.green); Debug.DrawLine(center.position, center.right * 3, Color.green); if (dot < 0) { 
    angle *= -1; angle += 360; } _2piAngleText.text ="2PI_angle: "+ angle.ToString(); float x = center.position.x + radius * Mathf.Sin(angle * Mathf.Deg2Rad); float z = center.position.z + radius * Mathf.Cos(angle * Mathf.Deg2Rad); sphere.transform.position = new Vector3(x, center.position.y, z); //旋转 Vector3 headPos = Camera.main.transform.position; Vector3 eulerAngles = Quaternion.LookRotation((headPos-arrow.position).normalized, Vector3.up).eulerAngles; eulerAngles.x = 0f; eulerAngles.z = 0f; arrow.eulerAngles = eulerAngles; } } 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/177402.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月26日 下午7:36
下一篇 2026年3月26日 下午7:36


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号