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

我们常常在游戏中遇到这种问题. 比如敌人遇到了主角就会朝他旋转过去. 或者判断主角在左边还是右边等等

效果图:

12

34

 

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

image

 

代码的实现:

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

posted @ 2015-08-10 00:32  盘子脸  阅读(1526)  评论(0编辑  收藏  举报