unity实现简单路径导航

实现一个点击地面,人物移动并显示导航路径的效果。

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

public class Player : MonoBehaviour
{
    NavMeshAgent agent;
    public LineRenderer line;
    Vector3 target;
    int PlaneLayer = 1 << 9;

    // Start is called before the first frame update
    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, 300, PlaneLayer))
            {
                if (hit.collider.tag == "Plane")
                {
                    target = hit.point;
                    agent.SetDestination(target);
                    Vector3[] posArr = GetPath();
                    line.positionCount = posArr.Length;
                    for (int i = 0; i < posArr.Length; i++)
                    {
                        line.SetPosition(i, posArr[i]);
                    }
                }
            }
        }
    }

    private void FixedUpdate()
    {
        if (Vector3.Distance(transform.position, target) <= 0.1f)
        {
            line.positionCount = 0;
        }
        else
        {
            Vector3[] posArr = GetPath();
            line.positionCount = posArr.Length;
            for (int i = 0; i < posArr.Length; i++)
            {
                line.SetPosition(i, posArr[i]);
            }
        }
    }

    Vector3[] GetPath()
    {
        //创建一个导航路径对象
        NavMeshPath path = new NavMeshPath();
        //给定了一个寻路的终点,agent组件会计算出一个最终的导航路线,
        //但是不会真的进行寻路,而是把计算出的路径存储在path对象中
        agent.CalculatePath(target, path);
        //path.corners拐点,不包含起点和终点
        Vector3[] posArr = new Vector3[path.corners.Length + 2];
        posArr[0] = transform.position;
        posArr[posArr.Length - 1] = target;
        for (int i = 0; i < path.corners.Length; i++)
        {
            posArr[i + 1] = path.corners[i];
        }
        return posArr;
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值