pool池

来源:互联网 发布:java反射获取类属性值 编辑:程序博客网 时间:2024/06/16 09:26
/**
 * Created by Administrator on 2017/5/27.
 */
//内存管理
cc.pool.putInPool(obj);//将对象放入对象缓冲池中
cc.pool.hasObject(objClass);//判断回收池中是否有可用的指定对象
cc.pool.removeObject(obj);//删除回收池中的指定对象
cc.pool.getFromPool(objClass);//从回收池回收指定对象
cc.pool.drainAllPools();//清空对象缓冲池


//对象缓存通过cc.pool.putInPool(object)函数实现,该函数会去调用该对象的unuse方法。一般情况下,我们会在unuse方法中完成对象被放入缓冲池钱的操作
//reuse则是当我们要从对象缓冲池中取出对象时所触发的函数,我们可以在这里完成对象的重新初始化,让它变为可用状态。简单来说,可用将unuse理解为“死亡”而非销毁,将reuse理解为“复活”而非创建。


var SupportPoolHero = cc.Sprite.extend({
    _hp:0,//血量
    _sp:0,//愤怒
    _mp:0,//魔法
    ctor:function(hp,mp,sp){
      this._super(res.sh_node_64_png);
      this.initData(hp,mp,sp);
    },
    initData:function(hp,mp,sp){
        this._hp,this._mp,this._sp = hp,mp,sp;
    },
    unuse: function () {
        this._hp = this._mp = this._sp = 0;
        this.retain();//使其引用计数+1,防止被内存回放
        this.removeFromParent(true);//
    },
    reuse:function(hp,mp,sp){//这里面的参数和ctor的参数一致
        this.initData(hp,mp,sp);
    }
});


SupportPoolHero.create = function(hp,mp,sp){
    //判断对象缓冲池中是否有可用对象
    if(cc.pool.hasObject(SupportPoolHero)){
        //从对象缓冲池中获取对象
        return cc.pool.getFromPool(SupportPoolHero,hp,mp,sp);
    }else{
        //创建一个新的对象
        return new SupportPoolHero(hp,mp,sp);
    }
};


//创建对象,并把它加入到对象缓冲池中
var support = SupportPoolHero.create(10,20,30);
if (support.getParent() == null) {
    this.addChild(support);
    cc.pool.putInPool(support);
}




//使用SpriteBatchNode
//SpriteBatchNode批处理渲染的用法很简单。主要分为三步
//第一步:将纹理加载到内存
//第二步:创建SpriteBatchNode
//第三步:创建精灵并将其加入到SpriteBatchNode
var BatchNodeLayer = cc.Layer.extend({
    batchNode:null,
    ctor:function(){
        //第一步:加载资源
        this.loadResource();
        //第二步:加载BatchNode
        this.loadBatchNode();
        //第三步:加载8000个精灵并将其添加到this.batchNode中
        this.loadSomePrince();
    },
    loadResource:function(){
        cc.textureCache.addImage(res.u13_price_png);
        cc.spriteFrameCache.addSpriteFrames(res.u13_price_plist);
    },
    loadBatchNode:function(){
        this.batchNode = new cc.SpriteBatchNode(res.u13_price_png);
        this.addChild(this.batchNode);
    },
    loadSomePrince:function(){
        var node = null;
        var pos = cc.p(0,0);
        for (var i = 0;i < 8000;i++){
            node = new cc.Sprite("#prince_stand_1.png");
            this.batchNode.addChild(node);


            pos.x = Math.random() * cc.winSize.width;
            pos.y = Math.random() * cc.winSize.height;


            node.setPosition(pos);
        }
    }
});