unity 自动寻路爬楼梯效果

unity 自动寻路爬楼梯效果_第1张图片

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

//自定义的类
public enum OffMeshLinkFlag
{
    //默认OffMeshLink没有开启的时候
    None,
    //OffMeshLink处于下楼的状态
    LadderDwon,
    //OffMeshLink处于爬楼梯的的状态
    LadderUp
}

public class Navigation : MonoBehaviour {

    Ray ray;
    RaycastHit hit;
    Vector3 target;
    private NavMeshAgent agent;
    private OffMeshLinkFlag flag = OffMeshLinkFlag.None;
    private float time = 0;
    private Rigidbody rg;
    private void Awake()
    {
        agent = GetComponent();
        target = transform.position;
        rg = GetComponent();
    }
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                target = new Vector3( hit.point.x,transform.position.y, hit.point.z);
                //设置目标后就可以移动了
                agent.destination = target;

                //agent.SetDestination(target);
                Debug.Log(agent.path.corners.Length);
            }
        }
        //自带移动效果
        //agent.SetDestination(target);
        if (agent.remainingDistance>agent.stoppingDistance)
        {
            //判断OffMeshLink是否开启 有没有开始上楼或下楼的状态
            if (agent.isOnOffMeshLink )
            {
                OffMeshLinkData link = agent.currentOffMeshLinkData;
                Vector3 center = (link.startPos + link.endPos) * 0.5f;
                //用来标记任务的状态
                if (flag == OffMeshLinkFlag.None)
                {
                    if (transform.position.y > center.y)
                    {
                        agent.GetComponent().material.color = Color.red;
                        flag = OffMeshLinkFlag.LadderDwon;
                        //下楼的速度是1
                        agent.speed = 1;
                    }
                    if (transform.position.y < center.y)
                    {
                        agent.GetComponent().material.color = Color.green;
                        flag = OffMeshLinkFlag.LadderUp;
                        //上楼的速度是0.5f
                        agent.speed = 0.5f;
                    }
                }
            }
            else //判断OffMeshLink是否关闭
            {
                agent.speed = 3.5f;
                flag = OffMeshLinkFlag.None;
            }
        }
    }
}

你可能感兴趣的:(Unity)