cocos creater 单例调用对象池出错
public static instance: bulletpool = null;
@property(cc.Prefab)
bulletPrefab: cc.Prefab = null;
// 在属性管理器上声明一个预制体类型,用于在属性管理器里挂载定义好的预制体
// LIFE-CYCLE CALLBACKS:
@property
interval: number = 1;
@property
bulletPools: cc.NodePool = null;
onLoad() {
this.onInstance();
this.bulletPools = new cc.NodePool();
//装填节点库
for (let i = 0; i < 50; i++) {
let nodes: cc.Node = cc.instantiate(this.bulletPrefab);
this.bulletPools.put(nodes);
};
this.schedule(this.onTimer, this.interval);
}
//启动单例
onInstance() {
if (bulletpool.instance == null) {
bulletpool.instance = this
}
else {
this.destroy()
return
}
}
onTimer() {
let node: cc.Node = null;
if (this.bulletPools.size() > 0) {
// 使用get方法获取闲置对象,这时候把存放批量创建节点的对象池nodePools当作参数传入get里,之后可以在预制体绑定的脚本内(假设是nodePrefab.ts),进行放回对象池操作
node = this.bulletPools.get();
} else {
// 如果没有闲置对象就通过预制体创建
node = cc.instantiate(this.bulletPrefab);
}
this.node.addChild(node);
}
bulletkilled(bullet: cc.Node) {
this.bulletPools.put(bullet);
}
}
@property
moveSpeed: number = 100;
@property
canvasHeight: number = 0;
@property
M: number = 0;
@property
N: number = 0;
// LIFE-CYCLE CALLBACKS:
start() {
this.node.rotation = this.M + Math.random() * (this.N - this.M);
}
update(dt: number) {
//旋转角度转化为弧度
let angle = this.node.rotation * 2 / 360 * Math.PI;
//计算基于Y轴的方向向量
let dir = cc.v2(Math.sin(angle), Math.cos(angle));
//方向向量进行单位化
dir.normalizeSelf();
//根据方向向量移动位置
this.node.x += dt * dir.x * this.moveSpeed;
this.node.y += dt * dir.y * this.moveSpeed;
let nodeone = this.node
if (this.node.y > this.canvasHeight) {
bulletpool.instance.bulletPools.put(this.node)
};
}
}