【Unity学习笔记】——使用unity自带寻路系统进行寻路

自动寻路步骤:

①  把场景中不动的物体勾选static

②  烘焙寻路网格

③  添加NavMeshAgent组件

④  给需要寻路的物体添加脚本

实现:

① 搭一个简易场景

放上enemy和player:

把场景设为静态

选择window→navigation,调出navigation面板,选择bake,形成一个蓝色路面,enemy将在这个蓝色路面上进行寻路

给寻路者(敌人)添加NavMeshAgent组件

把下面脚本挂到enemy上

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

/// <summary>
/// 寻路算法
/// </summary>
public class NavTest : MonoBehaviour {

    private NavMeshAgent agent;//寻路者
    public Transform target;//寻路目标

    private void Start()
    {
        agent = this.GetComponent<NavMeshAgent>();
    }

    private void Update()
    {
        if(agent!=null)
        {
            agent.SetDestination(target.position);//寻路算法
        }       
    }
}

运行,enemy自动靠近player

但是enemy和player会重合在一起

调Stopping Distance


如果没有player,点击哪就让AI往哪寻路呢?

把下面脚本挂到Camera上,为AI添加NavMeshAgent组件,同样需要烘焙一个NavMash

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class RayTest : MonoBehaviour {

    private Ray ray;
    private RaycastHit hit;//射线碰到的碰撞信息
    public GameObject navPlayer;//寻路的人
    private NavMeshAgent agent;

    private void Start()
    {
        agent = navPlayer.GetComponent<NavMeshAgent>();
    }

    private void Update ()
    {
        //射线起始位置
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray,out hit, 100) && Input.GetMouseButtonDown(0))
        {
            agent.SetDestination(hit.point);
            Debug.DrawLine(ray.origin, hit.point, Color.red);
        }
	}
}


  • 18
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值