67 lines
2.2 KiB
TypeScript
67 lines
2.2 KiB
TypeScript
import { _decorator, CCFloat, Component, Node, Prefab, randomRangeInt } from 'cc';
|
|
import ObjectPool from '../Pool/ObjectPool';
|
|
import { ScoreObject } from '../Environments/ScoreObject';
|
|
import { EventManger } from './EventManger';
|
|
import GameEvent from '../Events/GameEvent';
|
|
const { ccclass, property } = _decorator;
|
|
|
|
@ccclass('SpawnObjectManager')
|
|
export class SpawnObjectManager extends Component {
|
|
//#region singleton
|
|
private static _instance: SpawnObjectManager = null;
|
|
public static get instance(): SpawnObjectManager {
|
|
return SpawnObjectManager._instance;
|
|
}
|
|
//#endregion
|
|
|
|
@property({ type: Prefab, visible: true })
|
|
private _objects: Prefab[] = [];
|
|
@property({ type: Node, visible: true })
|
|
private _spawnPoints: Node[] = [];
|
|
@property({ type: CCFloat, visible: true, range: [1, 10], slide: true })
|
|
private _spawnTime;
|
|
|
|
private _pools: ObjectPool[] = [];
|
|
private _usedPoints: { [key: string]: Node } = {};
|
|
private _timer = 0;
|
|
|
|
protected onLoad(): void {
|
|
SpawnObjectManager._instance = this;
|
|
EventManger.instance.on(GameEvent.ScoreObjectRelease, this.onObjectRelease, this);
|
|
|
|
for (let i = 0; i < this._objects.length; i++) {
|
|
const prefab = this._objects[i];
|
|
this._pools[i] = new ObjectPool(prefab, 10, true, ScoreObject);
|
|
}
|
|
}
|
|
|
|
protected start(): void {
|
|
for (let i = 0; i < randomRangeInt(5, 10); i++) {
|
|
this.spawn();
|
|
}
|
|
}
|
|
|
|
protected update(dt: number): void {
|
|
this._timer += dt;
|
|
if (this._timer >= this._spawnTime) {
|
|
this._timer = 0;
|
|
this.spawn();
|
|
}
|
|
}
|
|
|
|
private spawn() {
|
|
if (Object.keys(this._usedPoints).length == this._spawnPoints.length) return;
|
|
var randomPool = this._pools[randomRangeInt(0, this._pools.length)];
|
|
do {
|
|
var randomPoint = this._spawnPoints[randomRangeInt(0, this._spawnPoints.length)];
|
|
} while (Object.values(this._usedPoints).indexOf(randomPoint) != -1);
|
|
const obj = randomPool.get(this.node);
|
|
obj.setWorldPosition(randomPoint.worldPosition);
|
|
this._usedPoints[obj.uuid] = randomPoint;
|
|
}
|
|
|
|
private onObjectRelease(obj: Node) {
|
|
delete this._usedPoints[obj.uuid];
|
|
}
|
|
}
|