using UnityEngine;
public class TestGetAnget : MonoBehaviour
{
public Transform m_target1;
public Transform m_target2;
public Transform target;
public Transform target1;
void Update()
{
GetAnglev3();
GetAngle(m_target1, m_target2);
}
void GetAnglev3()
{
Vector3 relative = target1.InverseTransformPoint(target.position);//將target.position轉換為target1的局部坐標
float angle = Mathf.Atan2(relative.x, relative.z) * Mathf.Rad2Deg;//rotationY等於0時,面朝向z軸,所以將z軸當作atan2里的x,x軸當作atan2里的y
target1.Rotate(0, angle, 0);//轉換局部坐標時已經把target1的旋轉角計算在內,這里的angle是rotationY的相對旋轉角
}
void GetAngle(Transform target1,Transform target2)
{
Vector3 dir = target1.position - target2.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
m_target1.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
Mathf.Atan2(float y,float x)
如果y和x都為正數,得到的結果也一定是正數。
計算rotationY時,使用Mathf.Atan2(+z,+x),得到的結果也一定是正數。
從俯視圖上看rotationY是順時針旋轉的,而+z和+x又一定是在右上方,因此得到的結果是相反的,所以rotationY=-Mathf.Atan2(z,x)才能得到正確的y軸旋轉角
或者使用Quaternion.AngleAxis(float angle,Vector3 axis)進行轉換。
float rotationY=Quaternion.AngleAxis(Mathf.Atan2(z,x)*Mathf.Rad2Deg, Vector3.down).eulerAngles.y;//得到正確的rotationY
//或
float rotationY=-Mathf.Atan2(z,x)*Mathf.Rad2Deg;//取負,得到正確的rotationY
將transform.rotationY朝向指定點的最簡便方法(只設置rotationY):
//targetPosition:目標位置
//transform:人物的Transform
//1.俯視圖中人物朝向z軸。
Vector3 relative=transform.InverseTransformPoint(targetPosition);
float rotationY=Mathf.Atan2(relative.x,relative.z)*Mathf.Rad2Deg;// atan2(x,z);
transform.Rotate(0,rotationY,0);
//2.俯視圖中人物朝向x軸。
Vector3 relative=transform.InverseTransformPoint(targetPosition);
float rotationY=-Mathf.Atan2(relative.z,relative.x)*Mathf.Rad2Deg;// -atan2(z,x);
transform.Rotate(0,rotationY,0);