游戏:鼠标打飞碟游戏
本周的作业是写一个鼠标打飞碟的游戏,具体的实现用工厂模式和前两次作业中用到的MVC模式来实现,从而实现人机交互与游戏模型分离的作用。
游戏总共有3个回合,每个回合的难度依次递增(虽然这次游戏设计的回合有点傻.....飞碟出现的速度也比较慢,轨道比较单一),但是最主要的作用是通过这次作业来充分了解工厂模式,和更加熟练的操作以前的MVC模式。
主要涉及到的新知识如下:
- 创建空对象并添加组件
- 创建基础类型游戏对象
- 从已知对象或预制克隆
创建空对象并添加组件的方法如下:
new GameObject();
new GameObject(string name);
new GameObject(string name, params Type[] components);
创建基础类型游戏对象的方法如下:
GameObject CreatePrimitive(PrimitiveType type);
从已知对象或预制克隆:
Instantiate<Transform>(brick, new Vector3(x,y,0),Quaterinion.identity);
检查一个对象是否拥有数据属性
GetComponent<T>()
游戏工厂模式设计
- 游戏对象的创建和销毁高成本,必须减少销毁次数。如:游戏中的子弹
- 屏蔽创建与销毁的业务逻辑,使程序易于拓展
工厂模式的UML图如下所示:
下面就是本次游戏的代码,头几个类基本上都是照搬前几次作业的类,工厂和飞碟等几个类则是参照老师的PPT,关键的场记和动作则是参照老师给的优秀博客的师兄的代码:师兄博客传送门
导演类的代码:
public class Director : System.Object {
public ISceneController currentSceneController { get; set; }
private static Director director;
private Director() {}
public static Director getInstance() {
if (director == null) {
director = new Director();
}
return director;
}
}
实现单实例的模版代码:
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour {
protected static T instance;
public static T Instance {
get {
if (instance == null) {
instance = (T)FindObjectOfType(typeof(T));
if (instance == null) {
Debug.LogError("An instance of " + typeof(T)
+ " is needed in the scene, but there is none.");
}
}
return instance;
}
}
}
记分器代码:
public class ScoreRecorder : MonoBehaviour {
private int Score;
private Dictionary<Color, int> ScoreDictionary = new Dictionary<Color,int>();
void Start() {
Score = 0;
ScoreDictionary.Add(Color.yellow,1);
ScoreDictionary.Add(Color.red,2);
ScoreDictionary.Add(Color.black,4);
}
public void Record(GameObject disk) {
Score += ScoreDictionary[disk.GetComponent<DiskData>().getDiskColor()];
Score += 2;
}
public void MinRecord() {
Score -= 2;
}
public int getScore(){
return Score;
}
public void Reset() {
Score = 0;
}
}
动作基类代码:
public class SSAction : ScriptableObject {
public bool enable = false;
public bool destroy = false;
public GameObject gameobject { get; set; }
public Transform transform { get; set; }
public ISSActionCallback callback { get; set; }
protected SSAction() {}
public virtual void Start () {
throw new System.NotImplementedException();
}
// Update is called once per frame
public virtual void Update () {
throw new System.NotImplementedException();
}
public void reset() {
enable = false;
destroy = false;
gameobject = null;
transform = null;
callb