纳金网

标题: 用NavMesh实现点击地面一点使角色避开障碍到达点击点 [打印本页]

作者: 烟雨    时间: 2015-8-30 00:47
标题: 用NavMesh实现点击地面一点使角色避开障碍到达点击点
  1. using UnityEngine;
  2. using System.Collections;

  3. public class TTT : MonoBehaviour {
  4.     private NavMeshAgent agent;
  5.     public float minDistance = 3;   //控制停下点与点击点间的距离
  6.         // Use this for initialization
  7.         void Start () {
  8.         agent = this.GetComponent<NavMeshAgent>();
  9.         }
  10.        
  11.         // Update is called once per frame
  12.         void Update () {
  13.         if (Input.GetMouseButtonDown(0))
  14.         {
  15.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  16.    
  17.             RaycastHit hit;
  18.             Physics.Raycast(ray, out hit);

  19.             Vector3 oriPos = transform.position;
  20.             Vector3 direction = hit.point - oriPos;
  21.             float length = (hit.point - oriPos).magnitude;
  22.             RaycastHit hitinfo;
  23.             bool isCollider = Physics.Raycast(oriPos, direction, out hitinfo, length);
  24.             if (isCollider)
  25.             {
  26.                 print("ddd");
  27.             }
  28.             SetDestination(hit.point);
  29.         }

  30.         if (agent.enabled)
  31.         {
  32.             if (agent.remainingDistance < minDistance && agent.remainingDistance != 0)
  33.             {
  34.                 agent.Stop();
  35.                 agent.enabled = false;
  36.             }
  37.         }
  38.         }

  39.     void SetDestination(Vector3 targetPos)
  40.     {
  41.         agent.enabled = true;
  42.         agent.SetDestination(targetPos);
  43.     }

  44.     void StopAuto()
  45.     {
  46.         if (agent.enabled)
  47.         {
  48.             agent.Stop();
  49.             agent.enabled = false;
  50.         }
  51.     }
  52. }
复制代码





欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5