Slash-The-Hordes/assets/Scripts/Game/Enemy/EnemySpawner.ts

50 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-11-08 18:45:57 +00:00
import { Component, Prefab, randomRange, Vec3, _decorator } from "cc";
import { GameTimer } from "../../Services/GameTimer";
import { ObjectPool } from "../../Services/ObjectPool";
import { Enemy } from "./Enemy";
2022-11-14 15:35:47 +00:00
import { EnemyMover } from "./EnemyMover";
2022-11-08 18:45:57 +00:00
const { ccclass, property } = _decorator;
@ccclass("EnemySpawner")
export class EnemySpawner extends Component {
@property(Prefab) private enemies: Prefab[] = [];
private enemyPool: ObjectPool<Enemy>;
private spawnTimer: GameTimer;
2022-11-14 15:35:47 +00:00
private enemyMover: EnemyMover;
2022-11-08 18:45:57 +00:00
2022-11-14 15:35:47 +00:00
public init(enemyMover: EnemyMover): void {
2022-11-08 18:45:57 +00:00
this.enemyPool = new ObjectPool(this.enemies[0], this.node, 5, Enemy);
2022-11-14 15:35:47 +00:00
this.spawnTimer = new GameTimer(1);
this.enemyMover = enemyMover;
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-14 15:35:47 +00:00
this.enemyMover.gameTick(deltaTime);
2022-11-08 18:45:57 +00:00
}
private spawnNewEnemy(): void {
const enemy = this.enemyPool.borrow();
enemy.node.active = true;
enemy.node.setPosition(new Vec3(randomRange(-300, 300), randomRange(-300, 300)));
enemy.setup();
enemy.DeathEvent.on(this.returnEnemyToPool, this);
2022-11-14 15:35:47 +00:00
this.enemyMover.addEnemy(enemy);
2022-11-08 18:45:57 +00:00
}
private returnEnemyToPool(enemy: Enemy): void {
enemy.DeathEvent.off(this.returnEnemyToPool);
this.enemyPool.return(enemy);
2022-11-14 15:35:47 +00:00
this.enemyMover.removeEnemy(enemy);
2022-11-08 18:45:57 +00:00
}
}