unity 简化ai移动脚本 挂上就能用那种

unity 简化ai移动脚本 挂上就能用那种,第1张

接上一篇自己又进行了简化

class="superseo">ai生成点的位置为中心移动

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

public class AIMove : MonoBehaviour
{
    //两点确定一个矩形范围
    Vector3 v1;
    Vector3 v2;
    //移动位置
    Vector3 pos;
    float time;
    //时间间隔
    float maxTime;
    //范围x平方
    float x;

    bool suo;
    bool suo1;
    // Start is called before the first frame update
    void Start()
    {
        startAi();
    }

    // Update is called once per frame
    void Update()
    {
        Move();
    }

    void startAi()
    {
        maxTime = Random.Range(3, 5);
        x = 2;
        v1 = transform.position + new Vector3(x, 0, x);
        v2 = transform.position + new Vector3(-x, 0 - x);
        //三维
        //v1 = transform.position + new Vector3(x, x, x);
        //v2 = transform.position + new Vector3(-x, -x - x);
        suo = true;
        suo1 = true;
    }
    //平面移动
    Vector3 RandV3(Vector3 a,Vector3 b)
    {
        return new Vector3(Random.Range(a.x,b.x),a.y,Random.Range(a.z,b.z));
    }

    //三维移动
    //Vector3 RandV3(Vector3 a, Vector3 b)
    //{
    //    return new Vector3(Random.Range(a.x, b.x), Random.Range(a.y,b.y), Random.Range(a.z, b.z));
    //}

    void Move()
    {
        if (suo)
        {
            if (suo1)
            {
                suo1 = false;
                pos = RandV3(v1, v2);
                transform.LookAt(pos);
            }
            //这里只能用MoveTowards()否则下面位置判断无效
            transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime);
            //到点
            if (transform.position == pos)
            {
                suo = false;
                maxTime = Random.Range(3, 5);
            }
        }
        else
        {
            time += Time.deltaTime;
        }

        if (time >= maxTime)
        {
            time = 0;
            suo = true;
            suo1 = true;
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/739707.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存