《XNA進階編程:Xbox 360和Windows》4-3

來源:互聯網
上載者:User
4.3遊戲組件

      TetrisGame類使用繼承自基類的Components屬性(在Microsoft.Xna.Framework.Game類中)來儲存所有的遊戲組件,您可以向這個列表中添加任何繼承自GameComponent類的自訂群組件類,當遊戲啟動或者更新的時候這個自訂類會被自動調用。但是在繪製遊戲的時候它是不被調用的,因為GameComponent類沒有Draw方法。不過,您還是可以實現自己的draw方法,或者直接使用包含Draw方法的DrawableGameComponent類。XNA does not have a direct Draw support for the game components; you have to call it yourself to make sure all components are called in the correct order。因為這個原因以及其他幾個原因(forcing you to use this model with almost no advantages, makes unit tests harder, your own game classes might be more effective or specific, and so on),在本書的稍後幾章中您不會使用太多的遊戲組件。It is generally a nice idea, but you can live without it because you have to create game components yourself anyway and you have to call Draw for them yourself too. Just for the Update method, it does not make much sense to use them

      正如我在第一章中所說,要讓大家分享自己的遊戲組件,以便其他人也可以使用它們。比如,一個幀計數器組件,甚至是一個fullblown 3D landscape rendering engine都可以作為一個遊戲組件來實現。but just because someone does not use a game component does not mean it is harder to copy over。例如,如果您有一個複雜的遊戲組件,像情境渲染模組,那它很可能包含一些其他類,而且使用自己的渲染引擎,which might not work out of the box in your engine if you just copy one file over。不管怎樣,移植外部的代碼經常需要進行很多的重構作業,直到這些代碼可以在您自己的遊戲引擎中工作。在XNA Framework beta 1中有一個圖形設計器,在XNA Game Studio Express中利用它您可以方便地向遊戲類甚至其他的遊戲組件中增刪組件,這樣您一行代碼都不用寫就可以增加遊戲特性。因為這個功能非常複雜,有很多bug,還不支援Xbox 360,在XNA Framework beta 2中就被捨棄了。

      It is not a sure thing that game components will not be used, and maybe it does not matter to most programmers that the designer is missing and you have to call the Draw methods yourself. Then a lot of game components might be available and it would be useful to know all the basics about them。本章的Tetris遊戲可以包含下面的幾個組件:

  • 網格:包含顏色方塊以及下落的方塊
  • 記分板:包含當前層級,得分,最高分,以及消除的方塊行數
  • 下一個要顯示的方塊
  • 其他:幀計數器,輸入處理等等

      在這裡我只把網格和下一個要顯示的方塊實現為組件,all the code is just way too simple for implementing several new classes just for them。如果您要重複使用記分板功能,您可以將其做成一個組件,但我還想不到我以後要做的什麼遊
戲會用到這樣的記分板。

      下面我們來進一步地瞭解一下Game類以及要增加的組件(4-2所示):

圖4-2

      灰色箭頭所指的方法會被自動調用,因為TetrisGrid和NextBlock都被添加到了Game類的Components屬性中。在TetrisGame.Draw中,調用了TetrisGrid類的Draw方法,而它又調用了NextBlock.Draw方法。TetrisGame只使用了TetrisGrid類,然後TetrisGrid類中又使用了NextBlock類。

      可以看出,在為這三個遊戲類應用遊戲組件的時候,您不得不考慮到其中的調用順序,這樣您就不必把所有的實現都裝進一個大類中,從而讓遊戲更有組織。雖然對於有經驗的程式員使用這樣的設計方式很不錯,但對於初學者來說提前在XNA中應用這種組件思想也是一個非常好的選擇。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.