Unity中物体如何移动到鼠标点击位置

  1. using UnityEngine;
  2. using System.Collections;
  3. public class Xunlu01 : MonoBehaviour {
    public GameObject target; //要进行移动的物体
    private NavMeshAgent agent;
    // Use this for initialization

  4. void Start () {
    //获取Nave 注意:一定要在控制面板上添加 NavMeshAgent
    agent = GetComponent< NavMeshAgent>();
    }
    // Update is called once per frame

  5. void Update () {
    //射线
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    //射线检测的信息
    RaycastHit hit;

    //第四个参数是一个表示二进制位的数 比如第四个参数为5的时候 只有第0层和第二层可以被检测
    if (Physics.Raycast(ray,out hit,LayerMask.NameToLayer("Ground")))
    {
        if (Input.GetMouseButtonDown(0)) //获取鼠标左键
        {
            agent.SetDestination(new Vector3(hit.point.x, agent.transform.position.y, hit.point.z)); 
        }
    }
    //自动检测
    //agent.SetDestination(target.transform.position);
    

    }
    }

  6. 效果如下图所示

物体的移动


版权声明:本文为Sxl1713232929原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。