关于Unity3D Quaternion类中的SetLookRotation方法

mac2025-11-15  5

原文参考链接:https://blog.csdn.net/QUAN2008HAPPY/article/details/39349837 SetLookRotation方法有两个重载: (1)public void SetLookRotation(Vector3 view); (2)public void SetLookRotation(Vector3 view, Vector3 up); 使用方法: Quaternion quaternion=Quaternion.identity; quaternion.SetLookRotation(v1,v2); transform.rotation=quaternion; **注意:**不可以直接使用transform.rotation.SetLookRotation(v1,v2)的方式来使用SetLookRotation方法,否则会不起作用。应该使用上述代码所示的方式,首先实例化一个Quaternion对象,然后再用Quaternion实例化出来的对象使用SetLookRotation,最后将其赋给transform.rotation。 那么v1,v2两个参数有什么作用呢? 1、transform.forward方向与v1方向相同; 2、transform.right垂直于由Vector3.zero、v1和v2三点构成的平面; 3、v2的作用除了与Vector3.zero和v1构成平面来决定transform.right的方向外,还用来决定transform.up的朝向,因为当transform.forward和transform.right方向确定后,transform.up方向剩下两种可能,到底选用哪一种便由v2来影响,transform.up方向的选取方式总会使得transform.up的方向和v2的方向的夹角小于或等于90度。当然,一般情况下v2.normalized和transform.up是不相同的。 4、当v1为Vector3.zero时方法失效,所以不要在使用此方法时把v1设置成Vector3.zero。 实例演示SetLookRotation方法的使用:

using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestSetLookRotation : MonoBehaviour { public Transform A, B, C; Quaternion q = Quaternion.identity; Vector3 v1; Vector3 v2; void Start() { v1=A.position; v2=B.position; } void Update () { //不可直接使用C.rotation.SetLookRotation(A.position,B.position); q.SetLookRotation(v1, v2); C.rotation = q; //分别绘制出v1、v2两条方向线,请在Scene视图中查看 Debug.DrawLine(Vector3.zero, A.position, Color.red); Debug.DrawLine(Vector3.zero, B.position, Color.green); //分别打印C.right与A、B的夹角 Debug.Log("C.right与A的夹角:" + Vector3.Angle(C.right, A.position)); Debug.Log("C.right与B的夹角:" + Vector3.Angle(C.right, B.position)); //C.up与B的夹角 Debug.Log("C.up与B的夹角:" + Vector3.Angle(C.up, B.position)); } }

图中物体C的红、绿、蓝箭头分别表示transform.right、transform.up、transform.forward三个方向。 由图三可直观的看到物体C的transform.forward与v1的方向一致,transform.right垂直于物体A、物体B与原点构成的平面。

因看了他人一篇博客有感而写,也是第一次在上写文章,不足之处还请谅解。 原文参考链接:https://blog.csdn.net/QUAN2008HAPPY/article/details/39349837

最新回复(0)