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

自动寻路步骤:

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

②  烘焙寻路网格

③  添加NavMeshAgent组件

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

实现:

① 搭一个简易场景

【Unity学习笔记】——使用unity自带寻路系统进行寻路_第1张图片

放上enemy和player:

【Unity学习笔记】——使用unity自带寻路系统进行寻路_第2张图片

把场景设为静态

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

【Unity学习笔记】——使用unity自带寻路系统进行寻路_第3张图片

【Unity学习笔记】——使用unity自带寻路系统进行寻路_第4张图片

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

【Unity学习笔记】——使用unity自带寻路系统进行寻路_第5张图片

【Unity学习笔记】——使用unity自带寻路系统进行寻路_第6张图片

把下面脚本挂到enemy上

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

/// 
/// 寻路算法
/// 
public class NavTest : MonoBehaviour {

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

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

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

运行,enemy自动靠近player

【Unity学习笔记】——使用unity自带寻路系统进行寻路_第7张图片

但是enemy和player会重合在一起

【Unity学习笔记】——使用unity自带寻路系统进行寻路_第8张图片

调Stopping Distance

【Unity学习笔记】——使用unity自带寻路系统进行寻路_第9张图片

【Unity学习笔记】——使用unity自带寻路系统进行寻路_第10张图片

如果没有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();
    }

    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);
        }
	}
}


你可能感兴趣的:(Unity3D)