和敌机1一样game中创建,对象池 预制资源 移除敌机2方法。
pre_enemy_2: cc.Prefab, this.enemy_2_pool = new cc.NodePool(); this.enemy_2_time = 0;//敌机创建的时间 create_enemy_2(){ let enemy_2 = null; if (this.enemy_2_pool.size()> 0) { // 通过 size 接口判断对象池中是否有空闲的对象 enemy_2 = this.enemy_2_pool.get(); //初始化敌机 enemy_2.init(); } else { // 如果没有空闲对象,也就是对象池中备用对象不够时,我们就用 cc.instantiate 重新创建 enemy_2 = cc.instantiate(this.pre_enemy_2); } enemy_2.parent = this.node; var pos =cc.v2(38,663); // 高663 enemy_2.setPosition(pos); }, on_enemy_2_killed: function (enemy_2) { // 销毁的时候 回收到 对象池里面 this.enemy_2_pool.put(enemy_2); },
cc.Class({ extends: cc.Component, properties: { }, onLoad() { this.init(); }, start() { }, update(dt) { if (game.isBgMove == true) { this.node.y = this.node.y - 2; } if(this.node.y<=-666){ game.on_enemy_2_killed(this.node); } }, init(){ this.isDie = false; this.hp=3;//生命是3 var anim = this.getComponent(cc.Animation); anim.play("enemy2_normal_Animation_Clip"); }, normal(){ var anim = this.getComponent(cc.Animation); anim.play("enemy2_normal_Animation_Clip"); }, hit(){ this.hp--; if(this.hp<=0){ this.die(); return; } var anim = this.getComponent(cc.Animation); anim.play("enemy2_hit_Animation_Clip"); anim.over = function(){ this.normal(); }.bind(this); //这里需要 绑定this不然获取不到 }, die(){ this.isDie = true; var anim = this.getComponent(cc.Animation); anim.play("enemy2_die_Animation_Clip"); anim.over = function(){ game.on_enemy_2_killed(this.node); } }, });
这样做,创建敌机 1 2 3 都可以做这个方法,减少重复代码
create_enemy(type) { //type = tag 1 2 3 let enemy = null; var str = ""; if (type == 1) { if (this.enemy_1_pool.size() > 0) { enemy = this.enemy_1_pool.get(); } else { enemy = cc.instantiate(this.pre_enemy_1); } str = "enemy_1"; } else if (type == 2) { if (this.enemy_2_pool.size() > 0) { enemy = this.enemy_2_pool.get(); } else { enemy = cc.instantiate(this.pre_enemy_2); } str = "enemy_2"; } else if (type == 3) { if (this.enemy_3_pool.size() > 0) { enemy = this.enemy_3_pool.get(); } else { enemy = cc.instantiate(this.pre_enemy_3); } str = "enemy_3"; } enemy.parent = this.node; var js = enemy.getComponent(str); if (js) { js.init(); } let x = -320 + parseInt(Math.random() * 640); //-320 到 320 console.log(x); var pos = cc.v2(x, 663); // 高663 enemy.setPosition(pos); }, on_enemy_killed: function (enemy_2, tag) { if (tag == 1) { this.enemy_1_pool.put(enemy_2); } else if (tag == 2) { this.enemy_2_pool.put(enemy_2); } else if (tag == 3) { this.enemy_3_pool.put(enemy_2); } },
站长微信:xiaomao0055
站长QQ:14496453