U3D 飞机大战(MVC模式)解析--面向对象编程思想
? 在自己研究U3D游戲的時候,看過一些人的簡單的游戲開發視頻,寫的不錯,只是個人是java web 開發的人,所以結合著MVC思想,對游戲開發進行了一番考慮。
如果能把游戲更加的思想化,分工化,開發便明了很多。
? 這是游戲開發的元素。基于面向對象開發,首先將這些游戲對象面向對象化
主角對象(GameObject):
??? 主角移動方法(function)--通過接收鍵盤事件,對主角進行移動。
??? 子彈發射方法(function)--實例化子彈,賦予子彈初始位置,調用子彈本身的移動方法。
敵人對象(GameObject):
敵人移動方法(function)--敵人初始化能夠移動方法
敵人發射子彈方法(function)--隔一段事件實例化子彈,賦予子彈初始化位置,調用子彈本身的移動方法。
子彈對象(GameObject):
? 威力屬性(property)--用來判斷對被擊中物體造成額度傷害。
?子彈移動方法(function)--子彈具有移動方法。
?
一般開發,主角對象(Sprite) 里面綁定一個腳本有一個Update,基本寫在Update函數里面,移動,子彈發射就能夠完成,
這樣,雖然能夠完成想要的效果,可是,這樣面向對象的思想不強,就如同,一條流水線組裝一樣,你一個人其實也都能夠搞定,可是如果分開來,一個人一個步驟,那樣就更加簡單了。
模擬一個普通腳本:
public class Player : MonoBehaviour{void Update(){if(按下xx鍵){move();}}//移動函數void move(){} }?也能夠實現通過控制鍵盤,使操作游戲對象進行移動
加入MVC的思想,思路就清晰些,模型,也就是對象,就只具有對象的屬性和方法,不具備實質性的行為,單純的就是個模型罷了
視圖就是游戲對象(GameObject)
模型就是該對象的屬性,方法的C##文件
控制器就是對加入的一些邏輯和調用模型的類
那么模擬下代碼
模型:
public class PlayerModel : MonoBehaviour{void Update(){}//移動函數void move(){} }控制器:
public class PlayerAction : MonoBehaviour{void Start(){PlayerModel play = gameobject.GetCompent<PlayerModel>();}void Update(){if(按下xx鍵){play.move();}}}這樣,就能夠把邏輯和調用都寫到控制器里面,不擾亂模型,模型就只有方法和屬性,不具備具體的行為
?
來一個例子:
代碼:PlayerAction
using UnityEngine; using System.Collections; /** Adminer:sun2955* http:www.yinghy.com* */ public class PlayerAction : MonoBehaviour {// 使用進行初始化void Start () {}//每一幀都會調用該函數void Update () {PlayerModel player = gameObject.GetComponent<PlayerModel>();player.Move();}//物理運動void FixedUpdate() {} }PlayerAction:
using UnityEngine; using System.Collections; /** Adminer:sun2955* http:www.yinghy.com* */ public class PlayerModel : MonoBehaviour {public GameObject xxx;//子彈對象private Vector2 speed = new Vector2(25, 25);private Vector2 movement;// 使用進行初始化void Start () {}//每一幀都會調用該函數void Update () {}//物理運動void FixedUpdate() {}public void Move() {float inputx = Input.GetAxis("Horizontal"); //獲得水平移動float inputy = Input.GetAxis("Vertical"); //獲得垂直移動Debug.LogError("inputx=" + inputx + "inputy=" + inputy);movement = new Vector2(inputx * speed.x, inputy * speed.y);if (Input.GetKey(KeyCode.K)){//發射子彈 實例化該子彈,得到子彈的對象,然后調用子彈的移動方法;GameObject xxgame = GameObject.Instantiate(xxx);xxgame.gameObject.transform.position = gameObject.transform.position;xxgame.gameObject.GetComponent<shootscript>().move();xxgame.gameObject.GetComponent<shootscript>().shootsound();}//這樣可以達到物理性質的運動gameObject.GetComponent<Rigidbody2D>().velocity = movement;} }出來的效果:
轉載于:https://www.cnblogs.com/sunxun/p/5066822.html
總結
以上是生活随笔為你收集整理的U3D 飞机大战(MVC模式)解析--面向对象编程思想的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos6.6安装python2.7
- 下一篇: 移动互联网教育领域或将出现新的风口?