Cocos creator 飞行游戏子弹的生成 使用对象池
game.js
cc.Class({
extends: cc.Component,
properties: {
// 飞机组件
hero: cc.Node,
// 子弹预制件
bulletPrefab: cc.Prefab,
},
onLoad() {
// 声明全局
window.game = this;
// 创建子弹对象池
this.bulletPool = new cc.NodePool();
// 控制子弹创建的时间间隔 变量
this.bulletTime = 0;
},
// 将对象返回对象池 方法
onBulletKilled: function (bullet) {
// bullet 应该是一个 cc.Node
this.bulletPool.put(bullet); // 和初始化时的方法一样,将节点放进对象池,这个方法会同时调用节点的 removeFromParent
},
// 创建子弹 对象池 方法
creatBullet: function () {
let bullet = null;
if (this.bulletPool.size() > 0) {
// 通过 size 接口判断对象池中是否有空闲的对象
bullet = this.bulletPool.get();
} else {
// 如果没有空闲对象,也就是对象池中备用对象不够时,我们就用 cc.instantiate 重新创建
bullet = cc.instantiate(this.bulletPrefab);
}
// 设置父节点
bullet.parent = this.node;
// 获取飞机的坐标位置
var pos = this.hero.getPosition();
bullet.setPosition(cc.v2(pos.x, pos.y + this.hero.height / 2 + 5));
},
// 移除子弹
removeAllBullet: function () {
// 获取子节点
var children = this.node.children;
for (let i = children.length - 1; i >= 0; i--) {
// 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
// 传入参数也可以是脚本的名称。
var js = children[i].getComponent("bullet");
if (js) {
this.onBulletKilled(children[i]);
}
}
},
update() {
if (this.isBgMove == true) {
this.setBgMove();
}
// 控制子弹创建的时间间隔
this.bulletTime++;
if (this.bulletTime == 5) {
// bulletTime重置为0
this.bulletTime = 0;
}
// cc.log(this.node.children.length);
},
});
bullet.js
cc.Class({
extends: cc.Component,
properties: {},
onLoad() {},
update(dt) {
this.node.y = this.node.y - 3;
},
});