AI自动行走逻辑

using System;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;


namespace Letang {
    public class AutoRunning : MonoBehaviour {
        //动画控制器
        public Animator animator;
        //是否循环
        public bool loop = false;
        //速度
        public float speed = 1.0f;
        public float speedOffset = 1.0f;
        //转弯速度
        public float rotateSpeed = 10.0f;
        //距离目标点多远算走到
        public float distanceRange = 10.0f;
        public Transform posObject;
        //初始位置
        protected Vector3 startPos;
        //当前行走目标点
        protected int curTarget = 0;

        private void Start() {
            startPos = transform.position;
            animator.SetFloat("speed", speed);
        }

        private void Update() {
#if UNITY_EDITOR
            animator.SetFloat("speed", speed);
#endif
            //移动
            transform.position = Vector3.Lerp(transform.position, transform.position + (transform.forward * speed * speedOffset), Time.deltaTime);
            Vector3 nextPos = posObject.Find(curTarget.ToString()).position;
            Vector3 direction = Vector3.Normalize(nextPos - transform.position);
            if (!direction.Equals(transform.forward)) {
                Quaternion newQuaternion = Quaternion.Lerp(Quaternion.Euler(transform.forward), Quaternion.Euler(direction), Time.deltaTime * rotateSpeed);
                //角度转成弧度
                transform.forward = Function.Deg2Rad(newQuaternion.eulerAngles);
            }
            //判断是否到达目的地
            if (Vector3.Distance(transform.position, nextPos) <= distanceRange) {
                //到达目的地
                curTarget++;
                if (posObject.childCount <= curTarget) {
                    curTarget = 0;
                    enabled = loop;
                    transform.position = startPos;
                }
            }
        }
    }
}

你可能感兴趣的:(Unity,AI,行走)