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

2020-10-20 10:25发布

在场景中创建一个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

链接:https://czhenya.blog.csdn.net/article/details/77338141

来源:CSDN
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。