2022-11-08 18:45:57 +00:00
|
|
|
import { Component, Prefab, randomRange, Vec3, _decorator } from "cc";
|
2022-11-16 11:26:20 +00:00
|
|
|
import { ISignal } from "../../Services/EventSystem/ISignal";
|
|
|
|
import { Signal } from "../../Services/EventSystem/Signal";
|
2022-11-08 18:45:57 +00:00
|
|
|
import { GameTimer } from "../../Services/GameTimer";
|
|
|
|
import { ObjectPool } from "../../Services/ObjectPool";
|
|
|
|
import { Enemy } from "./Enemy";
|
|
|
|
const { ccclass, property } = _decorator;
|
|
|
|
|
|
|
|
@ccclass("EnemySpawner")
|
|
|
|
export class EnemySpawner extends Component {
|
|
|
|
@property(Prefab) private enemies: Prefab[] = [];
|
|
|
|
|
2022-11-16 11:26:20 +00:00
|
|
|
public enemyAddedEvent: Signal<Enemy> = new Signal<Enemy>();
|
|
|
|
|
2022-11-08 18:45:57 +00:00
|
|
|
private enemyPool: ObjectPool<Enemy>;
|
|
|
|
private spawnTimer: GameTimer;
|
|
|
|
|
2022-11-16 11:26:20 +00:00
|
|
|
public init(): void {
|
|
|
|
this.enemyPool = new ObjectPool(this.enemies[0], this.node, 5, "Enemy");
|
2022-11-14 15:35:47 +00:00
|
|
|
this.spawnTimer = new GameTimer(1);
|
2022-11-08 18:45:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public gameTick(deltaTime: number): void {
|
|
|
|
this.spawnTimer.gameTick(deltaTime);
|
|
|
|
if (this.spawnTimer.tryFinishPeriod()) {
|
|
|
|
this.spawnNewEnemy();
|
|
|
|
}
|
2022-11-16 11:26:20 +00:00
|
|
|
}
|
2022-11-14 15:35:47 +00:00
|
|
|
|
2022-11-16 11:26:20 +00:00
|
|
|
public get EnemyAddedEvent(): ISignal<Enemy> {
|
|
|
|
return this.enemyAddedEvent;
|
2022-11-08 18:45:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private spawnNewEnemy(): void {
|
|
|
|
const enemy = this.enemyPool.borrow();
|
2022-11-16 11:26:20 +00:00
|
|
|
enemy.setup(new Vec3(randomRange(0, 300), randomRange(0, 800)));
|
2022-11-08 18:45:57 +00:00
|
|
|
|
|
|
|
enemy.DeathEvent.on(this.returnEnemyToPool, this);
|
2022-11-14 15:35:47 +00:00
|
|
|
|
2022-11-16 11:26:20 +00:00
|
|
|
this.enemyAddedEvent.trigger(enemy);
|
2022-11-08 18:45:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private returnEnemyToPool(enemy: Enemy): void {
|
|
|
|
enemy.DeathEvent.off(this.returnEnemyToPool);
|
|
|
|
this.enemyPool.return(enemy);
|
|
|
|
}
|
|
|
|
}
|