2014-02-16 104 views
0

我們是一對夫婦做遊戲。遊戲實體的數據存儲在嵌套數組中。頂層數組包含數組,每個數組對應一個實體。實體是指存儲在數組中的遊戲對象的參數和數組中引用的椋鳥對象。AS3,回收椋鳥物體

這些子數組有一個對Starling影片剪輯或Starling精靈的引用,以及對該實體約15個其他變量的引用。因此,變量不會以各種原因存儲在movieclip/sprite中。 Blitting的可能性就是其中之一。

問題是如何組織這個最好的方式,並最終實現回收椋鳥對象以減少垃圾收集問題。 我有三個建議,但我知道,別的可能會更好。

1) 具有用於每個類對象的一個​​「墓地」容器:一個用於小行星,一個用於playershots,一個用於.... 每當一個實體被破壞,相應的對象將轉到正確墓地。每當創建一個相同類的實體時,如果它持有任何一個,則從相應的容器中重用一個。

2) 所有被破壞的動畫片段和精靈的一個大容器。 每當一個精靈或動畫片段產生時,如果該容器包含任何東西,則從該容器中重用該對象。還應該設置正確的動畫。我不知道這是否需要大量的CPU或者可能。

3) 讓垃圾回收處理破壞的影片剪輯和精靈。不要回收它們。

+0

我正在使用flashpunk。所以,我試圖使用這種回收的東西來提高遊戲性能。但是,遊戲變得如此複雜,我也需要像你這樣的系統,我的意思是將實體的東西引用到數組和類似的東西上......但是,回收的東西已經成爲一個真正的問題,我嘗試了很多東西解決這個問題,但是每個解決方案都會造成另一個問題所以,我放棄了使用循環... –

回答

0

個人而言,當我想要做這樣的東西我重寫基類我想使用和添加一些代碼,做你想要的:

例如小行星類繼承MovieClip:

package 
{ 
    import starling.display.MovieClip; 
    import starling.textures.Texture; 

    public class Asteroid extends MovieClip 
    { 
     /** a object pool for the Asteroids **/ 
     protected static var _pool  :Vector.<Asteroid>; 
     /** the number of objects in the pool **/ 
     protected static var _nbItems :int; 
     /** a static variable containing the textures **/ 
     protected static var _textures :Vector.<Texture>; 
     /** a static variable containing the textures **/ 
     protected static var _fps  :int; 

     public function Asteroid() 
     { 
      super(_textures, 60); 
     } 

     /** a static function to initialize the asteroids textures and fps and to create the pool **/ 
     public static function init(textures:Vector.<Texture>, fps:int):void 
     { 
      _textures = textures; 
      _fps  = fps; 

      _pool  = new Vector.<Asteroid>(); 
      _nbItems = 0; 
     } 

     /** the function to call to release the object and return it to the pool **/ 
     public function release():void 
     { 
      // make sure it don't have listeners 
      this.removeEventListeners(); 
      // put it in the pool 
      _pool[_nbItems++] = this; 
     } 

     /** a static function to get an asteroid from the pool **/ 
     public static function get():Asteroid 
     { 
      var a :Asteroid; 
      if(_nbItems > 0) 
      { 
       a = _pool.pop(); 
       _nbItems--; 
      } 
      else 
      { 
       a = new Asteroid(); 
      } 
      return a; 
     } 

     /** a static function to destroy asteroids and the pool **/ 
     public static function dispose():void 
     { 
      for(var i:int = 0; i<_nbItems; ++i) _pool[i].removeFromParent(true); 
      _pool.length = 0; 
      _pool = null; 
     } 
    } 
} 

因此,你可以通過Asteroid.get();方法得到一個小行星,這將在游泳池中得到一個小行星,或者如果游泳池是空的,就創建一個小行星。

之前,你必須初始化的類的靜態函數Asteroid.init(textures, fps)

當你不需要再小行星你可以調用myAsteroid.release();這將小行星返回到池中的下次使用。

當您不再需要小行星時,您可以調用靜態Asteroid.dispose();來清除池。

希望這可以幫助你。