Unity 敌人状态的自动切换(巡游与追踪)

首先要建立一个2d寻路系统

>>点击此处查看

在任意一个空对象上绑定这个脚本控制脚本

(我选的这个空对象是寻路组件之一)

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

public class ScriptSelect: MonoBehaviour
{
    float changeTimer;//设定一个计时器,每过一段时间,机器人换一个方向运动
    public float changeTime = 10f;//计时器长度
    private bool status=true;
    // Start is called before the first frame update
    void Start()
    {
        change();
    }

    // Update is called once per frame
    void Update()
    {
        changeTimer -= Time.deltaTime;//计时器每一帧都减小
        if (changeTimer < 0)
        {
            change();
            changeTimer = changeTime;//改变方向后计时器重新初始化
        }
    }

    public void change()
    {
        if(status==true)
        {
            GameObject.Find("Robot/Robot").GetComponent<AIPath>().enabled = true;
            GameObject.Find("Robot/Robot").GetComponent<RobotControl>().enabled = false;
            status = false;
            return;
        }
        if (status == false)
        {
            GameObject.Find("Robot/Robot").GetComponent<AIPath>().enabled = false;
            GameObject.Find("Robot/Robot").GetComponent<RobotControl>().enabled = true;
            status = true;
            return;
        }
    }
}

用来在固定的时间段后切换敌人的状态

敌人身上有两个关键的脚本,一个是巡游(Robot Control),一个是自动寻路(AIPath)

在设定的时间内,两个脚本轮换启用

当一个运行时,另一个禁用

附完整教程:

Unity2d Rubys Adventure 课程设计报告

猜你喜欢

转载自blog.csdn.net/weixin_43673589/article/details/106532428