Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

Unity 物体跟随鼠标点击移动,判断物体是否在移动

$
0
0

在场景中创建一个Plane和一个Sphere以及3CubePlane做为地面,Sphere作为人物,Cube作为敌人。用户通过点击地面,使Sphere移动到点击的位置(不能使用导航网格寻路)Sphere如果接近敌人一定距离后,敌人会跟随Sphere行动。如果敌人在主角旁边静止2s则主角消失。

public class cube : MonoBehaviour {

    public Sphere sphere;
    float des; //与主角之间的距离

    // Use this for initialization
    void Start () {
        
    }
	
	// Update is called once per frame
	void Update () {
       
        des = Vector3.Distance(sphere.transform.position, this.gameObject.transform.position);
        if(des < 3 && des > 2)
        {       //看向主角并跟随;
            this.gameObject.transform.LookAt(sphere.transform.position);
            this.gameObject.transform.Translate(Vector3.forward * Time.deltaTime);

        }
        
    }

public class Sphere : MonoBehaviour {

    Ray ray;
    RaycastHit rh;
    float dis;      //鼠标与球的距离
    Vector3 tar;   //目标点

    private Vector3 lastPos;    //上一次运动停止的位置
    private float lastTime;     //上一次运动停止的时间

    // Use this for initialization
    void Start () {
        lastPos = transform.position;
        lastTime = 0;
    }
	
	// Update is called once per frame
	void Update () {

        if (Input.GetMouseButtonDown(0))   
        {      //左键,获得鼠标射线
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out rh))     
            {               
                if (rh.collider.name == "Plane")   //判碰撞物体是否是地面
                {
                    tar = rh.point;
                    
                    //Debug.Log(rh.point+"2");
                }
            }

        }
        dis = Vector3.Distance(this.gameObject.transform.position, tar);
        if (dis > 0.5f)   //鼠标点击与球的距离
        {
            this.gameObject.transform.LookAt(tar);
            this.gameObject.transform.Translate(Vector3.forward * Time.deltaTime);
        }
        if (dis < 3)
        {
            if (lastPos != transform.position)  //如果上次静止的位置和当前位置不相同,就更新上次静止的位置和时间
            {
                lastTime = Time.time;
                lastPos = transform.position;
            }
            if (Time.time - lastTime > 2)       //如果静止时间>2s  
            {
                lastTime = Time.time;
                Destroy(this.gameObject);
            }
        }
    }
}

作者:Czhenya 发表于2017/8/17 18:42:15 原文链接
阅读:28 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>