欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

unity自带的导航构建一个简单的地图寻路

程序员文章站 2022-05-22 16:01:32
...

1,利用navigation内置的运动控制

2,自己控制运动

3,运行时构建导航网格

重要组件

NavMesh Agent(导航网格代理 挂载在怪物上)

off-Mesh Link (网格链接)

NavMesh Obstacle(障碍,不经常移动勾选Carve)


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

public class controlPlayer : MonoBehaviour {
    private NavMeshAgent nav;

    public float rotateSmoothing = 7;       //转向速度
    public float speed = 5;

	// Use this for initialization
	void Start () {
        nav = this.GetComponent<NavMeshAgent>();
        nav.updatePosition = false;                 //禁用导航控制的运动和转向
        nav.updateRotation = false;
	}
	
	// Update is called once per frame
	void Update () {



        if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            bool isOn= Physics.Raycast(ray,out hit);
            if (isOn)
            {
                nav.SetDestination(hit.point);
                //nav.destination = hit.point;          //通过导航控制器控制

                nav.nextPosition = transform.position;


            }
        }
        if (nav.remainingDistance < 0.5f) return;
        nav.nextPosition = this.transform.position;     //把当前位置的设置给导航器的位置(灵魂)
        this.transform.position=nav.nextPosition;       //在把导航器的位置设置为当前的位置

        this.transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(nav.desiredVelocity), rotateSmoothing * Time.deltaTime);
        //nav.desiredVelocity 是最短路径的目标方向
        this.transform.Translate(Vector3.forward * speed * Time.deltaTime);
    }
}

利用NavMeshComponents进行实时Bake(NavMeshSurface挂载在地形上)


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class PlaceBuilder : MonoBehaviour {

    public GameObject builderPrefab;
    private NavMeshSurface surface;
	// Use this for initialization
	void Start () {
        surface = GetComponent<NavMeshSurface>();
    }
	
	// Update is called once per frame
	void Update () {

        if (Input.GetMouseButtonDown(1))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if(Physics.Raycast(ray, out hit))
            {
                GameObject go = GameObject.Instantiate(builderPrefab, hit.point, Quaternion.identity);
                go.transform.parent = this.transform;
                surface.BuildNavMesh();                //更新寻路
            }
        }
	}
}
unity自带的导航构建一个简单的地图寻路
相关标签: x