Unity---巡逻兵

UML图大致如下:


Unity---巡逻兵_第1张图片

相关解释:ObjectFactory生产巡逻兵Enemy,Action是动作基类,EnemyLoop为巡逻动作,EnemyChase为追逐动作。在其中用了观察者模式。
老师的要求:
1.巡逻兵是否为独立模块?
有一部分耦合(与工厂和计分器),主要在于观察者模式对这两部分进行了消息传递和绑定事件。
2.如果有多套AI,如何设计?
将AI扩展为Action的子类,需要换AI时只需要申请新的类型的Action即可。
下面是效果:



结构层次:

Unity---巡逻兵_第2张图片
Paste_Image.png

下面分析代码:
ObjectFactory.cs
一个简单工厂,生成Enemy实例
包含了一个Enemy之间的观察者互绑

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

public class ObjectFactory : MonoBehaviour {
    public GameObject Enemy;
    private List UsingEnemy;

    private static ObjectFactory _instance;
    public static ObjectFactory Instance
    {
        get
        {
            _instance = FindObjectOfType();
            if (_instance == null)
            {
                throw new System.NotImplementedException();
            }
            return _instance;
        }
    }


    // Use this for initialization
    void Start () {
        UsingEnemy = new List();
    }
    
    // Update is called once per frame
    void Update () {
        
    }

    public GameObject createEnemy(Vector3 pos)
    {
        UsingEnemy.Add(Instantiate(Enemy, pos, Quaternion.identity));
        return UsingEnemy[UsingEnemy.Count-1];
    }
    public void destroyEnemy()
    {
        for (int i = UsingEnemy.Count-1; i >= 0; i --)
        {
            GameObject temp = UsingEnemy[i];
            UsingEnemy.Remove(temp);
            Destroy(temp);
        }
    }
    public void bindObserver()
    {
        for (int i = 0; i < UsingEnemy.Count; i ++)
        {
            for (int j = 0; j < UsingEnemy.Count; j++)
            {
                UsingEnemy[i].GetComponent().OnGameOverEvent +=
                    UsingEnemy[j].GetComponent().setActionNull;
            }
        }
    }
}

SceneController.cs
场景管理器
在这里主要用于重新开始游戏的初始化设置

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

public class SceneController : System.Object {
    public bool gameover = false;

    private static SceneController _instance;
    public static SceneController Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new SceneController();
            }
            return _instance;
        }
    }

    public string getScore()
    {
        return ScoreCounter.Score.ToString();
    }

    public bool isGameOver()
    {
        return gameover;
    }

    public void startGame()
    {
        gameover = false;
        ObjectFactory.Instance.destroyEnemy();

        GameObject temp = GameObject.Find("Player");
        temp.transform.position = new Vector3(0, 0.75f, 0);

        ObjectFactory.Instance.createEnemy(new Vector3(-5, 0.75f, -5));
        ObjectFactory.Instance.createEnemy(new Vector3(-5, 0.75f, 5));
        ObjectFactory.Instance.createEnemy(new Vector3(5, 0.75f, -5));

        // 对所有gameobject进行观察者互绑
        ObjectFactory.Instance.bindObserver();
        ScoreCounter.Score = 0;

        // 设置Input模块Active
        temp.GetComponent().setInputActive(true);
    }
}

EnemyLoop.cs
这段代码描述了巡逻兵的巡逻AI
具体行为为在一个正方形中走多边形

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

public class EnemyLoop : Action {
    // 在一个为 loopsize 大小的四边形中走多边形,
    // 随机从任意一条边上选取任意一个点作为下一个target
    public const float loopsize = 7.0f;
    public const float speed = 2.0f;
    public Vector3 target;
    // 在四边形中的相对位置
    public Vector3 position;
    // 误差允许
    public const float EPS = 0.0001f;

    public static EnemyLoop getEnemyLoop(GameObject go)
    {
        EnemyLoop action = ScriptableObject.CreateInstance();
        action.gameobject = go;
        // 初始化在四边形的左下角
        action.position = new Vector3(0, 0, 0);
        // 计算首个target
        action.calcTarget();
        return action;
    }

    // Use this for initialization
    public override void Start () {
        
    }
    
    // Update is called once per frame
    public override void Update () {
        // 进行巡逻前进
        gameobject.transform.position = Vector3.MoveTowards(gameobject.transform.position, target, speed * Time.deltaTime);
        // 测试是否走到目标位置
        if (testArrived())
        {
            // 计算下一个巡逻目标
            calcTarget();
        }
    }

    public void calcTarget()
    {
        // 随机选择一条边:上方为0, 顺时针递增
        int randomedge = Random.Range(0, 4);
        // 随机选择边上一个点
        float randompoint = Random.Range(0, loopsize);
        Vector3 newposition = position;

        switch (randomedge)
        {
            case 0: newposition = new Vector3(randompoint, 0, loopsize); break;
            case 1: newposition = new Vector3(loopsize, 0, randompoint); break;
            case 2: newposition = new Vector3(randompoint, 0, 0); break;
            case 3: newposition = new Vector3(0, 0, randompoint); break;
        }
        // 从四边形坐标映射到世界坐标
        target = newposition - position + gameobject.transform.position;
        position = newposition;
    }

    public bool testArrived()
    {
        return Vector3.Distance(gameobject.transform.position, target) < EPS;
    }
}

EnemyChase.cs
这段描述了巡逻兵的追踪AI
简单的向着玩家当前位置走
加入了一个AILevel,作用后面会提到

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

public class EnemyChase : Action
{
    public GameObject player;
    int AILevel;

    public static EnemyChase getEnemyChase(GameObject go, GameObject player, int AILevel)
    {
        EnemyChase action = ScriptableObject.CreateInstance();
        action.gameobject = go;
        action.player = player;
        action.AILevel = AILevel;
        return action;
    }

    // Use this for initialization
    public override void Start()
    {

    }

    // Update is called once per frame
    public override void Update()
    {
        // 追踪玩家
        gameobject.transform.position = Vector3.MoveTowards(gameobject.transform.position, player.transform.position, AILevel * Time.deltaTime);
        // Debug.Log(gameobject.transform.position);
        // Debug.Log(player.transform.position);
    }

}

EnemyScript.cs
这段是挂载在Enemy上的脚本
具体实现细节请看注释

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

public class EnemyScript : MonoBehaviour {
    // 需要运行的动作
    Action action;
    // AI层级(模拟为追踪速度,每被甩掉一次自动增加AI层级)
    int AILevel = 2;
    // 玩家是否在侦测范围内
    GameObject Player;
    bool PlayerDetected = false;
    float DetectedRadius = 5.0f;

    // 观察者模式:当玩家离开Enemy的侦测范围时,向计分器发送基于当前AILevel的计分信息
    public delegate void LeaveEvent(float AILevel);
    public event LeaveEvent OnLeaveEvent;

    // 观察者模式:当玩家与其中一个Enemy碰撞时,通知其他Enemy灭活(绑定在SceneController中进行,不需解绑,直接Destroy)
    public delegate void gameOverEvent();
    public event gameOverEvent OnGameOverEvent;

    // 观察者模式:当玩家与其中一个Enemy碰撞时,通知玩家Input模块灭活
    public delegate void forbidInputEvent(bool isActive);
    public event forbidInputEvent OnForbidInputEvent;

    // Use this for initialization
    void Start () {
        Player = GameObject.Find("Player");
        action = EnemyLoop.getEnemyLoop(gameObject);
        // 绑定计分
        OnLeaveEvent += ScoreCounter.CountScore;
        // 绑定玩家
        OnForbidInputEvent += Player.GetComponent().setInputActive;
    }
    
    // Update is called once per frame
    void Update () {
        // 在侦测范围内寻找Player
        FindPlayer();
        if (action != null) {
            action.Update();
        }
        
    }

    void FindPlayer()
    {
        if (Vector3.Distance(Player.transform.position, gameObject.transform.position) < DetectedRadius)
        {
            // player第一次进入侦测范围
            if (!PlayerDetected)
            {
                // 申请追踪动作
                action = EnemyChase.getEnemyChase(gameObject, Player, AILevel);
                PlayerDetected = true;
            }
        }
        else
        {
            // Player离开侦测范围
            if (PlayerDetected)
            {
                // 申请巡逻动作
                action = EnemyLoop.getEnemyLoop(gameObject);
                // 传递信息给观察者
                OnLeaveEvent(AILevel);
                PlayerDetected = false;
                // 增加AI层级
                AILevel++;
            }
        }
    }

    // 与物体碰撞(判断持续)
    private void OnTriggerStay(Collider collider)
    {
        string Tag = collider.tag;
        // 与障碍物碰撞
        if (Tag == "RockTag" || Tag == "FenceTag" || Tag == "EnemyTag")
        {
            if (action is EnemyLoop)
            {
                // 重新计算下一个target
                (action as EnemyLoop).calcTarget();
            }
            // 追逐玩家过程中碰到障碍物(临时解决方法:重设动作为巡逻)(效果很差哈哈哈)
            else if (action is EnemyChase)
            {
                action = EnemyLoop.getEnemyLoop(gameObject);
            }
        }
    }
    // 与物体碰撞(判断初次)
    private void OnTriggerEnter(Collider collider)
    {
        string Tag = collider.tag;
        // 与玩家碰撞
        if (Tag == "PlayerTag")
        {
            // 游戏结束
            SceneController.Instance.gameover = true;
            action = null;
            // 通知其他Enemy停止动作(不使用SceneController的gameOver变量,降低耦合)
            OnGameOverEvent();
            // 灭活Input模块
            OnForbidInputEvent(false);
        }
    }

    public void setActionNull()
    {
        action = null;
    }
}

其他的UI,ScoreCounter之类的都是很简单的实现,不再赘述

相关还未解决的问题:
1.判断碰撞时(比如玩家撞墙)会发生抖动,使得玩家不再处于平面上,而会产生漂浮。
2.巡逻兵速度过快时会卡入墙内
3.巡逻兵模块未完全解耦,不能单独一个预制即可拿来使用。
4.一些AI很丑,比如追踪玩家时如果遇到障碍物应该怎么做?
5.对于观察者模式存在的意义还不甚明了,使用得还不够规范。

你可能感兴趣的:(Unity---巡逻兵)