码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-08-10 01:55:27      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

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

效果图:

技术分享技术分享

技术分享技术分享

 

向量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

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

标签:

原文地址:http://www.cnblogs.com/plateFace/p/4716799.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!