飞碟游戏改进
改進飛碟游戲
- 游戲內容要求:
- 按 adapter模式 設計圖修改飛碟游戲
- 使它同時支持物理運動與運動學(變換)運動
要求是使用adapter模式修改飛碟游戲,但是我的代碼并不適合這樣修改。
適合使用adapter模式有三種情況:
- 系統需要使用現有的類,而此類的接口不符合系統的需要。
- 想要建立一個可以重復使用的類,用于與一些彼此之間沒有太大關聯的一些類,包括一些可能在將來引進的類一起工作,這些源類不一定有一致的接口。
- 通過接口轉換,將一個類插入另一個類系中。
對于放飛飛碟,我是用一個moveable類賦予飛碟運動的能力,這個moveable類并沒有上層接口,其本身是一種能力。飛碟通過擁有一個moveable的實例獲得了運動學運動的能力。其中moveable的代碼如下:
using System.Collections; using System.Collections.Generic; using UnityEngine;public class Moveable: MonoBehaviour {int move_speed = 1;// change frequentlyint moving_status; // 0->not moving, 1->moving to middle, 2->moving to destVector3 dest;Vector3 middle;void Update() {if (moving_status == 1) {// Debug.Log(transform.position);moveTo(transform.position, dest, move_speed * Time.deltaTime);// ufoAction.moveTo(this.gameObject,transform.position, dest, move_speed * Time.deltaTime);// transform.position = Vector3.MoveTowards (transform.position, dest, move_speed * Time.deltaTime);if (transform.position == dest) {moving_status = 0;}}}void moveTo(Vector3 pos, Vector3 des, float speed){this.transform.position = Vector3.MoveTowards (pos, des, speed);}public void setDestination(Vector3 _dest,int speed) {move_speed = speed;dest = _dest;moving_status = 1;}public void reset() {moving_status = 0;} }使用moveable的示例如下:
public class UFO { public GameObject ufo;public Moveable ms;void start(){ufo = Object.Instantiate (Resources.Load ("Prefabs/disk1", typeof(GameObject)), Vector3.zero, Quaternion.identity, null) as GameObject;ms = ufo.AddComponent(typeof(Moveable)) as Moveable;ms.setDestination(new Vector3(0,0,0),10);} }這種情況下要滿足題目第二個條件并不適合用適配器模式,因為Moveable本身不依賴于任何一個GameObject,也沒有上層接口。
不過,要讓游戲同時支持物理運動與運動學(變換)運動在我的代碼中非常容易實現,這也是我不想強行使用適配器模式的原因之一。為了滿足要求,我們只需要增添一個physicMoveable類即可,飛碟類同時擁有moveable的一個實例和physicMoveable的一個實例,也就是說,飛碟類同時擁有了物理運動和變換運動的能力。只需要在Fly函數中決定使用哪一種運動能力即可。
因此,整份代碼需要修改的地方只有兩處。
這樣實現的好處有以下幾點:
-
代碼復用率高,因此工作量小。上個版本所有的代碼都可以復用,只需要增加一個類以及修改一個類即可
-
更改運動模式方便。只需要注釋一行代碼以及取消一行注釋就可以實現(以下代碼選自BaseCode.cs中的UFO類):
// 選擇哪個就取消哪個的注釋pt.moveTo(start,des,speed);// ms.setDestination(des,speed);
github傳送門
總結
- 上一篇: 3.Python3标准库--数据结构
- 下一篇: 程序员职业发展