他強調把程式碼的功能性分開的軟體開發過程。
Component based Programming在遊戲引擎裡被廣泛得運用,如Unity3D:
Component Based Programming由三個主要構成:
System: 處理Render、Physics、Particle。
Entries:又稱為GameObject,出現在遊戲引擎畫面上的物件(游標、地板…等)。
Component:一個Entries可能會包含數個Componets,為這物件添加功能如Box Collider(物件碰撞網格)、Mesh Renderer(Render畫面)。
以XNA來說:
Componet最常用的莫過於GameComponent、DrawableGameComponent
在使用XNA 當產生一個DrawableGameCompoent 就必須 override三個Method
1: public override void LoadContent(){}
2: public override void Draw(){}
3: public override void Update(){}
在XNA中每新增一個Compoent時,都要使用Components.Add(XXComponent),使用過XNA的人想必都不陌生吧。
當沒有Xna 的Framework,那是必須自己寫一個Framework(如PlayStationMobile),這時在Design Patterns有個模式 Composite Pattern:
Composite:將物件組合成樹形結構已表示[部分-整體]的層次結構。使的用戶對單個物件和組合物件的使用具有一致性。
1: abstract class Component
2: {3: protected String name;
4: public Component(String name)
5: {6: this.name = name;
7: }8: public abstract void Add(Component c);
9: public abstract void Remove(Component c);
10: public abstract void Display(int depth);
11: }1: class Leaf:Component
2: {3: public Leaf(string name)
4: :base(name){}
5: public override void Add(Component c)
6: {7: Console.WriteLine("Can't add to a leaf");
8: }9: public override void Remove(Component c)
10: {11: Console.WriteLine("Can't remove frome a leaf");
12: }13: publoc override void Display()
14: {15: Console.WriteLine(new String('-',depth) + name);
16: } 17: }1: class Composite:Component
2: {3: private List<Component>children = new List<Component>();
4: public Composite(string name)
5: :base(name){}
6: public override void Add(Component C)
7: { 8: children.Add(C); 9: }10: public override void Remove(Component C)
11: { 12: children.Add(C); 13: }14: public override void Display(int depth)
15: {16: Console.WriteLine(new String('-',depth) + name);
17: foreach(Component conponent in children)
18: { 19: component.Display(depth + 2); 20: } 21: } 22: }在這裡假設我要管理敵人的Manager的類別、管理子彈的類別、管理遊戲狀態的類別,其在主程式:
1: static void Main(String[] args)
2: {3: Composite root = new Composite("root");
4: 5: Composite enemyManager = new Composite("EnemyManager");
6: enemyManager.Add(new Leaf("Enemy A"));
7: enemyManager.Add(new Leaf("Enemy B"));
8: root.Add(enemyManager); 9: 10: Composite bulletManager = new Composite("BulletManager");
11: root.Add(bulletManager); 12: 13: Leaf gameManager = new Leaf("GameManager");
14: root.Add(gameManager); 15: }
這遊戲內物件關係就變成:
這技術不管用在2D Engine 或 3D Engine都廣泛使用,所以當使用Engine做遊戲開發這是很重要的知識。
No comments:
Post a Comment