點(diǎn)積公式為:
A·B = |A| * |B| * cos<A, B>
A·B = Ax·Bx + Ay·By + Az·Bz
再結(jié)合余弦曲線可以知道:
當(dāng)夾角在[0,90], [270, 360]區(qū)間內(nèi)氓辣,cosx > 0
當(dāng)夾角在[90, 270]區(qū)間內(nèi),cosx < 0
所以:
- 當(dāng)你跟目標(biāo)點(diǎn)方向的叉積 > 0 時(shí)账蓉,說明你面向它枚碗;
- 當(dāng)你跟目標(biāo)點(diǎn)方向的叉積 < 0 時(shí),說明你背對它铸本。
Vector3 dirA = transform.forward;
Vector3 dirB = target.position - transform.position;
float dp = Vector3.Dot(dirA, dirB);
if(dp > 0)
Debug.Log("target is in the front");
else if(dp < 0)
Debug.Log(target is in the back");
叉積公式為:
// 值為向量肮雨,且此向量垂直于dirA,dirB構(gòu)成的平面
A * B = A * B * sin<A, B>
A * B = (Ay·Bz-Az·By, Az·Bx-AxBz, AxBy-AyBx)
Unity使用左手坐標(biāo)系箱玷,所以:
- 當(dāng)dirC.y > 0 時(shí)怨规,目標(biāo)點(diǎn)在右側(cè)
- 當(dāng)dirC.y > 0 時(shí),目標(biāo)點(diǎn)在左側(cè)
// a的當(dāng)前朝向
Vector3 vec3Forward = a.transform.TransformDirection(Vector3.forward);
// 目標(biāo)方向
Vector3 vec3Target = b.transform.transform.position - a.transform.position;
// 計(jì)算叉乖
Vector3 vec3Cross = Vector3.Cross( vec3Forward, vec3Target );
// 計(jì)算轉(zhuǎn)角
float dAngle = Vector3.Angle( vec3Forward, vec3Target ); // Angle方法始終返回最小角
// 根據(jù)左手法則锡足,y向上波丰,說明目標(biāo)在右邊,y向下舶得,說明目標(biāo)在左邊
if( vec3Cross.y > 0 )
{
// 向右轉(zhuǎn)
a.transform.Rotate( cube.transform.up, dAngle )
}
else
{
// 向左轉(zhuǎn)
a.transform.Rotate( cube.transform.up, -dAngle )
}