首先还是得熟悉一下uml图,基本上和前面的游戏差不多,主要就是加了事件的订阅和发布

首先是Director类和两个接口,和之前的差不多,主要就是调整一下接口的函数,从上面的UML图可以看出,IUserAction的函数主要就是用于GUI中以便调用
public interface ISceneControl
{
void LoadResources();
}
public interface IUserAction
{
void playerMoving(float x, float z);
bool getState();
void setState(bool state);
}
public class Director : System.Object
{
public ISceneControl currentSceneController { get; set; }
private static Director director;
private Director()
{
}
public static Director getInstance()
{
if (director == null)
{
director = new Director();
}
return director;
}
}
下面就是IUserGUI类,主要用于渲染出一个界面,在游戏开始结束时进行显示信息,和用于开始游戏等操作
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IUserGUI : MonoBehaviour {
private IUserAction act;
// Use this for initialization
void Start () {
act = Director.getInstance().currentSceneController as IUserAction;
}
// Update is called once per frame
void Update () {
if(!act.getState())
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
act.playerMoving(x, z);
}
}
void OnGUI()
{
if(act.getState())
{
GUI.Label(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 200, 400, 400), "GAMEOVER" + " your score is " + Singleton<ScoreRecorder>.Instance.score.ToString());
if (GUI.Button(new Rect(Screen.width / 2 - 45, Screen.height / 2 - 45, 90, 90), "Restart"))
{
act.setState(false);
Singleton<ScoreRecorder>.Instance.Reset();
}
}
else
{
GUI.Label(new Rect(2 * Screen.width / 3, 0, 400, 400), "score: " + Singleton<ScoreRecorder>.Instance.score.ToString());
}
}
}
下面就是工厂模式的一些类,PlayerData是添加到player上的组件,用来纪录用户在地图的那个方块。然后PatrolData就是挂在Patrol上的组件,纪录了patrol在那个地区巡逻,和是不是在追击用户,还有originPos就是追击动作之前的位置,方便回去继续巡逻。工厂类就是用来生成patrol和回收的,和之前的飞碟和射箭差不多。
public class PlayerData : MonoBehaviour
{
public int areaIndex;
}
public class PatrolData : MonoBehaviour
{
public int currentIndex;
public bool isFollow = false;
public GameObject player;
public Vector3 originPos;
}
public class PatrolFactory : MonoBehaviour {
private GameObject firstPatrol = null;
private List<PatrolData> used = new List<PatrolData>();
private List<PatrolData> free = new List<PatrolData>();
private void Awake()
{
firstPatrol = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("prefab/patrol"), Vector3.zero, Quaternion.identity);
firstPatrol.SetActive(false);
}
public GameObject GetPatrol()
{
GameObject newPatrol = null;
if (free.Count > 0)
{
newPatrol = free[0].gameObject;
free.Remove(free[0]);
}
else
{
newPatrol = GameObject.Instantiate<GameObject>(firstPatrol, Vector3.zero, Quaternion.identity);
newPatrol.AddComponent<PatrolData>();
}
used.Add(newPatrol.GetComponent<PatrolData>());
newPatrol.name = newPatrol.GetInstanceID().ToString();
return newPatrol;
}
public void FreePatrol(Game