2014-02-16 66 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();来清除池。

希望这可以帮助你。