上期介绍了Vector.Dot可以用来判断敌人处于自身的前方or后方,那么这期就是通过叉乘来判断敌人处于自身的左方or右方
public class CrossTest : MonoBehaviour
{
public GameObject sphere;
public GameObject cube;
// Start is called before the first frame update
void Start()
{
}
private void Update() {
var v=sphere.transform.position-cube.transform.position;
Vector3 cross=Vector3.Cross(cube.transform.forward,v);
Debug.DrawLine(cube.transform.position,cube.transform.forward*10,Color.red);
Debug.DrawLine(cube.transform.position,sphere.transform.position,Color.green);
Debug.DrawRay(cube.transform.position,cross,Color.blue);
}
}
可以看到,敌人位于自身右边时(x轴正方向)根据右手定则,叉乘的结果方向向上
将球移动至自身右边时
根据这个特性,我们可以根据叉乘结果的正负来判断敌人位于自身的左边or右边。
public class CrossTest : MonoBehaviour
{
public GameObject sphere;
public GameObject cube;
// Start is called before the first frame update
void Start()
{
}
private void Update() {
var v=sphere.transform.position-cube.transform.position;
Vector3 cross=Vector3.Cross(cube.transform.forward,v);
Debug.DrawLine(cube.transform.position,cube.transform.forward*10,Color.red);
Debug.DrawLine(cube.transform.position,sphere.transform.position,Color.green);
Debug.DrawRay(cube.transform.position,cross,Color.blue);
if(cross.y>0)
{
Debug.Log("在右边");
}else{Debug.Log("在左边");}
}
}