查看: 665|回复: 0
打印 上一主题 下一主题

[其他] 用NavMesh实现点击地面一点使角色避开障碍到达点击点

[复制链接]

9903

主题

126

听众

7万

积分

首席设计师

Rank: 8Rank: 8

纳金币
53488
精华
316

最佳新人 热心会员 灌水之王 活跃会员 突出贡献 荣誉管理 论坛元老

跳转到指定楼层
楼主
发表于 2015-8-30 00:47:28 |只看该作者 |倒序浏览
  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. }
复制代码
分享到: QQ好友和群QQ好友和群 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
转播转播0 分享淘帖0 收藏收藏0 支持支持0 反对反对0
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

手机版|纳金网 ( 闽ICP备2021016425号-2/3

GMT+8, 2025-8-13 02:22 , Processed in 0.065179 second(s), 28 queries .

Powered by Discuz!-创意设计 X2.5

© 2008-2019 Narkii Inc.

回顶部