您的位置:首页 > 其它

叉乘实现角色和敌人的位置判断(左上,左下,右上,右下)

2015-08-10 00:32 591 查看
我们常常在游戏中遇到这种问题. 比如敌人遇到了主角就会朝他旋转过去. 或者判断主角在左边还是右边等等

效果图:













 

向量A,B的叉乘获得一个垂直于他们的C向量,我们可以通过这上面的值来判断敌人四个区域的某一区





 

代码的实现:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

public Transform a;
public Transform b;
public TextMesh text;
public TextMesh oneResult;
public TextMesh twoResult;

public float distance;
private float dot;

public void Update()
{
//B在A的前方,A是主角,B是敌人
Vector3 toOther = a.transform.position - b.position;

//获取的Y可以判断敌人 在人物的左边和右边
Vector3 chaCheng1 = Vector3.Cross(a.forward, toOther);
Vector3 chaCheng2 = Vector3.Cross(a.right, toOther);

oneResult.text = chaCheng1.ToString();
twoResult.text = chaCheng2.ToString();

Debug.Log("第一次值: " + chaCheng1);

//获取的Y可以判断敌人 在人物的前边和后边
Debug.Log("第二次值: " + chaCheng2);

if (chaCheng1.y > 0 && chaCheng2.y > 0)
{
text.text = "位置: 左上";
}
if (chaCheng1.y < 0 && chaCheng2.y < 0)
{
text.text = "位置: 右下";

}
if (chaCheng1.y > 0 && chaCheng2.y < 0)
{
text.text = "位置: 左下";

}
if (chaCheng1.y < 0 && chaCheng2.y > 0)
{
text.text = "位置: 右上";

}

}

}


 

项目下载地址:  http://yunpan.cn/cdYkG48mxIGGD  访问密码 54c3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: