| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104 |
- import { _decorator, Node, Label, Vec3, Prefab, find, UITransform, resources, RigidBody2D, instantiate } from 'cc';
- import { sp } from 'cc';
- import { ConfigManager, EnemyConfig } from '../Core/ConfigManager';
- import { EnemyComponent } from '../CombatSystem/EnemyComponent';
- import { EnemyInstance } from './EnemyInstance';
- import { BaseSingleton } from '../Core/BaseSingleton';
- import { SaveDataManager } from '../LevelSystem/SaveDataManager';
- import { LevelConfigManager } from '../LevelSystem/LevelConfigManager';
- import EventBus, { GameEvents } from '../Core/EventBus';
- import { Wall } from './Wall';
- const { ccclass, property } = _decorator;
- @ccclass('EnemyController')
- export class EnemyController extends BaseSingleton {
- // 仅类型声明,实例由 BaseSingleton 维护
- public static _instance: EnemyController;
- // 敌人预制体
- @property({
- type: Prefab,
- tooltip: '拖拽Enemy预制体到这里'
- })
- public enemyPrefab: Prefab = null;
- // 敌人容器节点
- @property({
- type: Node,
- tooltip: '拖拽enemyContainer节点到这里(Canvas/GameLevelUI/enemyContainer)'
- })
- public enemyContainer: Node = null;
- // 金币预制体
- @property({ type: Prefab, tooltip: '金币预制体 CoinDrop' })
- public coinPrefab: Prefab = null;
- // 移除Toast预制体属性,改用事件机制
- // @property({
- // type: Prefab,
- // tooltip: 'Toast预制体,用于显示波次提示'
- // })
- // public toastPrefab: Prefab = null;
- // === 生成 & 属性参数(保留需要可在内部自行设定,Inspector 不再显示) ===
- private spawnInterval: number = 3;
- // === 默认数值(当配置文件尚未加载时使用) ===
- private defaultEnemySpeed: number = 50;
- private defaultAttackPower: number = 10;
- private defaultHealth: number = 30;
- @property({ type: Node, tooltip: '拖拽 TopFence 节点到这里' })
- public topFenceNode: Node = null;
- @property({ type: Node, tooltip: '拖拽 BottomFence 节点到这里' })
- public bottomFenceNode: Node = null;
- // 关卡配置管理器节点
- @property({
- type: Node,
- tooltip: '拖拽Canvas/LevelConfigManager节点到这里,用于获取LevelConfigManager组件'
- })
- public levelConfigManagerNode: Node = null;
- // 主墙体组件
- private wallComponent: Wall = null;
- // 游戏区域边界 - 改为public,让敌人实例可以访问
- public gameBounds = {
- left: 0,
- right: 0,
- top: 0,
- bottom: 0
- };
- // 活跃的敌人列表
- private activeEnemies: Node[] = [];
-
- // 游戏是否已开始
- private gameStarted: boolean = false;
-
- // 墙体节点
- private wallNodes: Node[] = [];
-
- // 是否正在清理敌人(用于阻止清理时触发游戏胜利判断)
- private isClearing: boolean = false;
- // 配置管理器
- private configManager: ConfigManager = null;
-
- // 关卡配置管理器
- private levelConfigManager: LevelConfigManager = null;
-
- // 当前关卡血量倍率
- private currentHealthMultiplier: number = 1.0;
- @property({
- type: Node,
- tooltip: '敌人数量显示节点 (EnemyNumber)'
- })
- public enemyCountLabelNode: Node = null;
- @property({
- type: Node,
- tooltip: '波数显示Label (WaveNumber)'
- })
- public waveNumberLabelNode: Node = null;
- // 当前波次敌人数据
- private totalWaves: number = 1;
- private currentWave: number = 1;
- private currentWaveTotalEnemies: number = 0;
- private currentWaveEnemiesKilled: number = 0;
- private currentWaveEnemiesSpawned: number = 0; // 当前波次已生成的敌人数量
- private currentWaveEnemyConfigs: any[] = []; // 当前波次的敌人配置列表
- // 暂停前保存的敌人状态
- private pausedEnemyStates: Map<Node, {
- velocity: any,
- angularVelocity: number,
- isMoving: boolean,
- attackTimer: number
- }> = new Map();
- /**
- * BaseSingleton 首次实例化回调
- */
- protected init() {
- // 获取配置管理器实例
- this.configManager = ConfigManager.getInstance();
-
- // 获取关卡配置管理器实例
- if (this.levelConfigManagerNode) {
- this.levelConfigManager = this.levelConfigManagerNode.getComponent(LevelConfigManager) || null;
- if (!this.levelConfigManager) {
- // LevelConfigManager节点上未找到LevelConfigManager组件
- }
- } else {
- // levelConfigManagerNode未通过装饰器绑定,请在编辑器中拖拽Canvas/LevelConfigManager节点
- this.levelConfigManager = null;
- }
- // 如果没有指定enemyContainer,尝试找到它
- if (!this.enemyContainer) {
- this.enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
- if (!this.enemyContainer) {
- // 找不到enemyContainer节点,将尝试创建
- }
- }
-
- // 获取游戏区域边界
- this.calculateGameBounds();
-
- // 查找墙体节点和组件
- this.findWallNodes();
- // 直接通过拖拽节点获取 Wall 组件
- if (this.topFenceNode && this.topFenceNode.getComponent(Wall)) {
- this.wallComponent = this.topFenceNode.getComponent(Wall);
- } else if (this.bottomFenceNode && this.bottomFenceNode.getComponent(Wall)) {
- this.wallComponent = this.bottomFenceNode.getComponent(Wall);
- } else {
- // 未找到墙体组件,将无法处理墙体伤害
- }
-
- // 确保enemyContainer节点存在
- this.ensureEnemyContainer();
- // UI节点已通过装饰器拖拽绑定,无需find查找
- if (!this.enemyCountLabelNode) {
- // enemyCountLabelNode 未通过装饰器绑定,请在编辑器中拖拽 Canvas-001/TopArea/EnemyNode/EnemyNumber 节点
- }
- if (!this.waveNumberLabelNode) {
- // waveNumberLabelNode 未通过装饰器绑定,请在编辑器中拖拽 Canvas-001/TopArea/WaveInfo/WaveNumber 节点
- }
-
- // 初始化敌人数量显示
- this.updateEnemyCountLabel();
- // 监听游戏事件
- this.setupEventListeners();
- }
- /**
- * 设置事件监听器
- */
- private setupEventListeners() {
- const eventBus = EventBus.getInstance();
-
- // 监听暂停事件
- eventBus.on(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
-
- // 监听恢复事件
- eventBus.on(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
-
- // 监听游戏成功/失败事件
- eventBus.on(GameEvents.GAME_SUCCESS, this.onGameEndEvent, this);
- eventBus.on(GameEvents.GAME_DEFEAT, this.onGameDefeatEvent, this);
-
- // 监听敌人相关事件
- eventBus.on(GameEvents.ENEMY_UPDATE_COUNT, this.onUpdateEnemyCountEvent, this);
- eventBus.on(GameEvents.ENEMY_START_WAVE, this.onStartWaveEvent, this);
- eventBus.on(GameEvents.ENEMY_START_GAME, this.onStartGameEvent, this);
- eventBus.on(GameEvents.ENEMY_SHOW_START_WAVE_PROMPT, this.onShowStartWavePromptEvent, this);
-
- // 监听子弹发射检查事件
- eventBus.on(GameEvents.BALL_FIRE_BULLET, this.onBallFireBulletEvent, this);
-
- // 监听获取最近敌人事件
- eventBus.on(GameEvents.ENEMY_GET_NEAREST, this.onGetNearestEnemyEvent, this);
-
- // 监听重置敌人控制器事件
- eventBus.on(GameEvents.RESET_ENEMY_CONTROLLER, this.onResetEnemyControllerEvent, this);
-
- // 监听重置相关事件
- eventBus.on(GameEvents.CLEAR_ALL_GAME_OBJECTS, this.onClearAllGameObjectsEvent, this);
- eventBus.on(GameEvents.RESET_ENEMY_CONTROLLER, this.onResetEnemyControllerEvent, this);
- }
-
- /**
- * 获取当前关卡的血量倍率
- */
- private async getCurrentHealthMultiplier(): Promise<number> {
- if (!this.levelConfigManager) {
- return 1.0;
- }
-
- try {
- const saveDataManager = SaveDataManager.getInstance();
- const currentLevel = saveDataManager ? saveDataManager.getCurrentLevel() : 1;
- const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
-
- if (levelConfig && levelConfig.levelSettings && levelConfig.levelSettings.healthMultiplier) {
- return levelConfig.levelSettings.healthMultiplier;
- }
- } catch (error) {
- console.warn('[EnemyController] 获取关卡血量倍率失败:', error);
- }
-
- return 1.0;
- }
- /**
- * 处理游戏暂停事件
- */
- private onGamePauseEvent() {
- this.pauseAllEnemies();
- this.pauseSpawning();
- }
- /**
- * 处理游戏恢复事件
- */
- private onGameResumeEvent() {
- this.resumeAllEnemies();
-
- // 通过事件检查游戏状态,决定是否恢复敌人生成
- this.resumeSpawning();
- }
- /**
- * 处理游戏结束事件
- */
- private onGameEndEvent() {
- this.stopGame(false); // 停止游戏但不清除敌人
- }
-
- /**
- * 处理游戏失败事件
- */
- private onGameDefeatEvent() {
- this.stopGame(true); // 停止游戏并清除所有敌人
- }
-
- /**
- * 处理清除所有游戏对象事件
- */
- private onClearAllGameObjectsEvent() {
- this.clearAllEnemies(false); // 清除敌人但不触发事件
- }
-
- /**
- * 处理重置敌人控制器事件
- */
- private onResetEnemyControllerEvent() {
- this.resetToInitialState();
- }
-
- /**
- * 处理子弹发射检查事件
- */
- private onBallFireBulletEvent(data: { canFire: (value: boolean) => void }) {
- // 检查是否有活跃敌人
- const hasActiveEnemies = this.hasActiveEnemies();
- data.canFire(hasActiveEnemies);
- }
- /**
- * 处理获取最近敌人事件
- */
- private onGetNearestEnemyEvent(data: { position: Vec3, callback: (enemy: Node | null) => void }) {
- const { position, callback } = data;
- if (callback && typeof callback === 'function') {
- const nearestEnemy = this.getNearestEnemy(position);
- callback(nearestEnemy);
- }
- }
- /**
- * 暂停所有敌人
- */
- private pauseAllEnemies(): void {
- const activeEnemies = this.getActiveEnemies();
-
- for (const enemy of activeEnemies) {
- if (!enemy || !enemy.isValid) continue;
- // 保存敌人状态
- const rigidBody = enemy.getComponent(RigidBody2D);
- if (rigidBody) {
- this.pausedEnemyStates.set(enemy, {
- velocity: rigidBody.linearVelocity.clone(),
- angularVelocity: rigidBody.angularVelocity,
- isMoving: true,
- attackTimer: 0 // 可以扩展保存攻击计时器
- });
- // 停止敌人运动
- rigidBody.linearVelocity.set(0, 0);
- rigidBody.angularVelocity = 0;
- rigidBody.sleep();
- }
- // 暂停敌人AI组件(如果有的话)
- const enemyAI = enemy.getComponent('EnemyAI');
- if (enemyAI && typeof (enemyAI as any).pause === 'function') {
- (enemyAI as any).pause();
- }
- // 暂停敌人动画(如果有的话)
- const animation = enemy.getComponent('Animation');
- if (animation && typeof (animation as any).pause === 'function') {
- (animation as any).pause();
- }
- }
- }
- /**
- * 恢复所有敌人
- */
- private resumeAllEnemies(): void {
- const activeEnemies = this.getActiveEnemies();
-
- for (const enemy of activeEnemies) {
- if (!enemy || !enemy.isValid) continue;
- const savedState = this.pausedEnemyStates.get(enemy);
- if (savedState) {
- const rigidBody = enemy.getComponent(RigidBody2D);
- if (rigidBody) {
- // 恢复敌人运动
- rigidBody.wakeUp();
- rigidBody.linearVelocity = savedState.velocity;
- rigidBody.angularVelocity = savedState.angularVelocity;
- }
- }
- // 恢复敌人AI组件
- const enemyAI = enemy.getComponent('EnemyAI');
- if (enemyAI && typeof (enemyAI as any).resume === 'function') {
- (enemyAI as any).resume();
- }
- // 恢复敌人动画
- const animation = enemy.getComponent('Animation');
- if (animation && typeof (animation as any).resume === 'function') {
- (animation as any).resume();
- }
- }
- // 清空保存的状态
- this.pausedEnemyStates.clear();
- }
- // 计算游戏区域边界
- private calculateGameBounds() {
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (!gameArea) {
- return;
- }
- const uiTransform = gameArea.getComponent(UITransform);
- if (!uiTransform) {
- return;
- }
- const worldPos = gameArea.worldPosition;
- const width = uiTransform.width;
- const height = uiTransform.height;
- this.gameBounds = {
- left: worldPos.x - width / 2,
- right: worldPos.x + width / 2,
- top: worldPos.y + height / 2,
- bottom: worldPos.y - height / 2
- };
- }
- // 查找墙体节点
- private findWallNodes() {
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (gameArea) {
- this.wallNodes = [];
- for (let i = 0; i < gameArea.children.length; i++) {
- const child = gameArea.children[i];
- if (child.name.includes('Wall') || child.name.includes('wall') || child.name.includes('墙')) {
- this.wallNodes.push(child);
- }
- }
- }
- }
- /**
- * 查找墙体组件
- */
- private findWallComponent() {
- // 查找墙体节点上的Wall组件
- for (const wallNode of this.wallNodes) {
- this.wallComponent = wallNode.getComponent(Wall);
- if (this.wallComponent) {
- break;
- }
- }
-
- }
- // 移除 initWallHealthDisplay 和 updateWallHealthDisplay 方法,这些现在由Wall组件处理
- // 确保enemyContainer节点存在
- ensureEnemyContainer() {
- // 如果已经通过拖拽设置了节点,直接使用
- if (this.enemyContainer && this.enemyContainer.isValid) {
- return;
- }
-
- // 尝试查找节点
- this.enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
- if (this.enemyContainer) {
- return;
- }
-
- // 如果找不到,创建新节点
- const gameLevelUI = find('Canvas/GameLevelUI');
- if (!gameLevelUI) {
- console.error('找不到GameLevelUI节点,无法创建enemyContainer');
- return;
- }
-
- this.enemyContainer = new Node('enemyContainer');
- gameLevelUI.addChild(this.enemyContainer);
- if (!this.enemyContainer.getComponent(UITransform)) {
- this.enemyContainer.addComponent(UITransform);
- }
- }
- // 游戏开始
- startGame() {
- // 游戏状态检查现在通过事件系统处理
-
- this.gameStarted = true;
-
- // 确保enemyContainer节点存在
- this.ensureEnemyContainer();
-
- // 确保先取消之前的定时器,避免重复调度
- this.unschedule(this.spawnEnemy);
-
- // 开始生成敌人
- this.schedule(this.spawnEnemy, this.spawnInterval);
- }
- // 游戏结束
- stopGame(clearEnemies: boolean = true) {
- this.gameStarted = false;
-
- // 停止生成敌人
- this.unschedule(this.spawnEnemy);
-
- // 只有在指定时才清除所有敌人
- if (clearEnemies) {
- // 清除敌人,在重置状态时不触发事件,避免错误的游戏成功判定
- this.clearAllEnemies(false);
- }
- }
- // 生成敌人
- async spawnEnemy() {
- if (!this.gameStarted || !this.enemyPrefab) {
- return;
- }
-
- // 游戏状态检查现在通过事件系统处理
-
- // 检查是否已达到当前波次的敌人生成上限
- if (this.currentWaveEnemiesSpawned >= this.currentWaveTotalEnemies) {
- this.unschedule(this.spawnEnemy); // 停止定时生成
- return;
- }
-
- // 随机决定从上方还是下方生成
- const fromTop = Math.random() > 0.5;
-
- // 实例化敌人
- const enemy = instantiate(this.enemyPrefab) as Node;
- enemy.name = 'Enemy'; // 确保敌人节点名称为Enemy
-
- // 添加到场景中
- const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
- if (!enemyContainer) {
- return;
- }
-
- enemyContainer.addChild(enemy);
-
- // 生成在对应线(Line1 / Line2)上的随机位置
- const lineName = fromTop ? 'Line1' : 'Line2';
- const lineNode = enemyContainer.getChildByName(lineName);
- if (!lineNode) {
- console.warn(`[EnemyController] 未找到 ${lineName} 节点,取消本次敌人生成`);
- enemy.destroy();
- return;
- }
- // 在对应 line 上随机 X 坐标
- const spawnWorldX = this.gameBounds.left + Math.random() * (this.gameBounds.right - this.gameBounds.left);
- const spawnWorldY = lineNode.worldPosition.y;
- const worldPos = new Vec3(spawnWorldX, spawnWorldY, 0);
- const localPos = enemyContainer.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
- enemy.position = localPos;
-
- // === 根据配置设置敌人 ===
- const enemyComp = enemy.addComponent(EnemyInstance);
- // 确保敌人数据库已加载
- await EnemyInstance.loadEnemyDatabase();
- let enemyConfig: EnemyConfig = null;
- let enemyId: string = null;
-
- if (this.configManager && this.configManager.isConfigLoaded()) {
- // 优先使用当前波次配置中的敌人类型
- if (this.currentWaveEnemyConfigs.length > 0) {
- const configIndex = this.currentWaveEnemiesSpawned % this.currentWaveEnemyConfigs.length;
- const enemyTypeConfig = this.currentWaveEnemyConfigs[configIndex];
- const enemyType = enemyTypeConfig.enemyType || enemyTypeConfig;
-
- // 尝试通过敌人名称映射获取ID
- enemyId = enemyType;
- if (this.configManager.getNameToIdMapping) {
- const mapping = this.configManager.getNameToIdMapping();
- if (mapping && mapping[enemyType]) {
- enemyId = mapping[enemyType];
- }
- }
-
- enemyConfig = this.configManager.getEnemyById(enemyId) || this.configManager.getRandomEnemy();
- } else {
- enemyConfig = this.configManager.getRandomEnemy();
- enemyId = enemyConfig?.id || 'normal_zombie';
- }
- }
- // 获取当前关卡的血量倍率
- const healthMultiplier = await this.getCurrentHealthMultiplier();
-
- if (enemyConfig && enemyId) {
- try {
- const cfgComp = enemy.addComponent(EnemyComponent);
- cfgComp.enemyConfig = enemyConfig;
- cfgComp.spawner = this;
- } catch (error) {
- console.error(`[EnemyController] 添加EnemyComponent失败:`, error);
- }
- // 使用EnemyInstance的新配置系统
- try {
- // 设置敌人配置
- enemyComp.setEnemyConfig(enemyId);
-
- // 应用血量倍率
- const baseHealth = enemyComp.health || this.defaultHealth;
- const finalHealth = Math.round(baseHealth * healthMultiplier);
- enemyComp.health = finalHealth;
- enemyComp.maxHealth = finalHealth;
-
- console.log(`[EnemyController] 敌人 ${enemyId} 配置已应用,血量: ${finalHealth}`);
- } catch (error) {
- console.error(`[EnemyController] 应用敌人配置时出错:`, error);
- // 使用默认值
- const finalHealth = Math.round(this.defaultHealth * healthMultiplier);
- enemyComp.health = finalHealth;
- enemyComp.maxHealth = finalHealth;
- enemyComp.speed = this.defaultEnemySpeed;
- enemyComp.attackPower = this.defaultAttackPower;
- }
- // 加载动画
- this.loadEnemyAnimation(enemy, enemyConfig);
- } else {
- // 使用默认配置
- try {
- enemyComp.setEnemyConfig('normal_zombie'); // 默认敌人类型
- const baseHealth = enemyComp.health || this.defaultHealth;
- const finalHealth = Math.round(baseHealth * healthMultiplier);
- enemyComp.health = finalHealth;
- enemyComp.maxHealth = finalHealth;
- } catch (error) {
- console.error(`[EnemyController] 应用默认敌人配置时出错:`, error);
- // 使用硬编码默认值
- const finalHealth = Math.round(this.defaultHealth * healthMultiplier);
- enemyComp.health = finalHealth;
- enemyComp.maxHealth = finalHealth;
- enemyComp.speed = this.defaultEnemySpeed;
- enemyComp.attackPower = this.defaultAttackPower;
- }
- }
- // 额外的属性设置
- enemyComp.spawnFromTop = fromTop;
- enemyComp.targetFence = find(fromTop ? 'Canvas/GameLevelUI/GameArea/TopFence' : 'Canvas/GameLevelUI/GameArea/BottomFence');
- enemyComp.movingDirection = Math.random() > 0.5 ? 1 : -1;
- enemyComp.targetY = fromTop ? this.gameBounds.top - 50 : this.gameBounds.bottom + 50;
- enemyComp.changeDirectionTime = 0;
- enemyComp.controller = this;
-
- // 更新敌人血量显示
- enemyComp.updateHealthDisplay();
-
- // 添加到活跃敌人列表
- this.activeEnemies.push(enemy);
-
- // 增加已生成敌人计数
- this.currentWaveEnemiesSpawned++;
- // 生成敌人时不更新敌人数量显示,避免重置计数
- }
- // 清除所有敌人
- clearAllEnemies(triggerEvents: boolean = true) {
- // 设置清理标志,阻止清理过程中触发游戏胜利判断
- if (!triggerEvents) {
- this.isClearing = true;
- }
-
- // 如果不触发事件,先暂时禁用 notifyEnemyDead 方法
- const originalNotifyMethod = this.notifyEnemyDead;
-
- if (!triggerEvents) {
- // 临时替换为空函数
- this.notifyEnemyDead = () => {};
- }
-
- for (const enemy of this.activeEnemies) {
- if (enemy && enemy.isValid) {
- enemy.destroy();
- }
- }
-
- // 恢复原来的方法
- if (!triggerEvents) {
- this.notifyEnemyDead = originalNotifyMethod;
- }
-
- this.activeEnemies = [];
-
- // 重置清理标志
- if (!triggerEvents) {
- this.isClearing = false;
- }
-
- // 清除敌人时不更新敌人数量显示,避免重置计数
- }
- // 获取所有活跃的敌人
- getActiveEnemies(): Node[] {
- // 过滤掉已经无效的敌人
- this.activeEnemies = this.activeEnemies.filter(enemy => enemy && enemy.isValid);
- return this.activeEnemies;
- }
- // 获取当前敌人数量
- getCurrentEnemyCount(): number {
- return this.getActiveEnemies().length;
- }
- // 获取最近的敌人节点
- public getNearestEnemy(fromPosition: Vec3): Node | null {
- const enemies = this.getActiveEnemies();
- if (enemies.length === 0) return null;
- let nearestEnemy: Node = null;
- let nearestDistance = Infinity;
- for (const enemy of enemies) {
- const distance = Vec3.distance(fromPosition, enemy.worldPosition);
- if (distance < nearestDistance) {
- nearestDistance = distance;
- nearestEnemy = enemy;
- }
- }
- return nearestEnemy;
- }
- // 检查是否有活跃敌人
- public hasActiveEnemies(): boolean {
- const activeCount = this.getActiveEnemies().length;
- return activeCount > 0;
- }
-
- // 调试方法:检查enemyContainer中的实际敌人节点
- private debugEnemyContainer() {
- const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
- if (!enemyContainer) {
- return;
- }
-
- let enemyNodeCount = 0;
- enemyContainer.children.forEach((child, index) => {
- if (child.name === 'Enemy' || child.name.includes('Enemy')) {
- enemyNodeCount++;
- }
- });
- }
-
- // 调试方法:强制清理无效敌人引用
- public debugCleanupEnemies() {
- const beforeCount = this.activeEnemies.length;
- this.activeEnemies = this.activeEnemies.filter(enemy => enemy && enemy.isValid);
- const afterCount = this.activeEnemies.length;
- return afterCount;
- }
- // 获取游戏是否已开始状态
- public isGameStarted(): boolean {
- return this.gameStarted;
- }
- // 暂停生成敌人
- public pauseSpawning(): void {
- if (this.gameStarted) {
- this.unschedule(this.spawnEnemy);
- }
- }
- // 恢复生成敌人
- public resumeSpawning(): void {
- // 游戏状态检查现在通过事件系统处理
-
- if (!this.gameStarted) {
- return;
- }
-
- // 检查是否已达到当前波次的敌人生成上限
- if (this.currentWaveEnemiesSpawned >= this.currentWaveTotalEnemies) {
- return;
- }
-
- // 确保先取消之前的定时器,避免重复调度
- this.unschedule(this.spawnEnemy);
- this.schedule(this.spawnEnemy, this.spawnInterval);
- }
- // 敌人受到伤害
- damageEnemy(enemy: Node, damage: number, isCritical: boolean = false) {
- if (!enemy || !enemy.isValid) return;
-
- // 游戏状态检查现在通过事件系统处理
-
- // 获取敌人组件
- const enemyComp = enemy.getComponent(EnemyInstance);
- if (!enemyComp) return;
-
- // 减少敌人血量
- enemyComp.takeDamage(damage, isCritical);
-
- // 检查敌人是否死亡
- if (enemyComp.health <= 0) {
- // 从活跃敌人列表中移除
- const index = this.activeEnemies.indexOf(enemy);
- if (index !== -1) {
- this.activeEnemies.splice(index, 1);
- }
- // 敌人死亡时不在这里更新数量显示,由GameManager统一管理
- // 销毁敌人
- enemy.destroy();
- }
- }
- // 墙体受到伤害 - 现在委托给Wall组件
- damageWall(damage: number) {
- if (this.wallComponent) {
- this.wallComponent.takeDamage(damage);
- } else {
- console.warn('[EnemyController] 墙体组件未找到,无法处理伤害');
- }
- }
- // 游戏结束
- gameOver() {
- // 停止游戏,但不清除敌人
- this.stopGame(false);
-
- // 通过事件系统触发游戏失败
- const eventBus = EventBus.getInstance();
- eventBus.emit(GameEvents.GAME_DEFEAT);
- }
- update(dt: number) {
- if (!this.gameStarted) return;
-
- // 更新所有敌人
- for (let i = this.activeEnemies.length - 1; i >= 0; i--) {
- const enemy = this.activeEnemies[i];
- if (!enemy || !enemy.isValid) {
- this.activeEnemies.splice(i, 1);
- continue;
- }
-
- // 敌人更新由各自的组件处理
- // 不再需要检查敌人是否到达墙体,因为敌人到达游戏区域后会自动攻击
- // 敌人的攻击逻辑已经在EnemyInstance中处理
- }
- }
-
- public getCurrentWallHealth(): number {
- return this.wallComponent ? this.wallComponent.getCurrentHealth() : 0;
- }
-
- public forceEnemyAttack() {
- const activeEnemies = this.getActiveEnemies();
-
- for (const enemy of activeEnemies) {
- const enemyComp = enemy.getComponent(EnemyInstance);
- if (enemyComp) {
- // 直接调用damageWall方法进行测试
- this.damageWall(enemyComp.attackPower);
- }
- }
- }
- /** 供 EnemyInstance 在 onDestroy 中调用 */
- public notifyEnemyDead(enemyNode?: Node) {
-
- // 如果正在清理敌人,不触发任何游戏事件
- if (this.isClearing) {
- if (enemyNode) {
- const idx = this.activeEnemies.indexOf(enemyNode);
- if (idx !== -1) {
- this.activeEnemies.splice(idx, 1);
- }
- }
- return;
- }
-
- if (enemyNode) {
- const idx = this.activeEnemies.indexOf(enemyNode);
- if (idx !== -1) {
- this.activeEnemies.splice(idx, 1);
- } else {
- console.warn(`[EnemyController] 警告:尝试移除的敌人不在activeEnemies数组中!`);
- }
- // 移除EnemyController内部的击杀计数,统一由GameManager管理
- // this.currentWaveEnemiesKilled++;
- // 敌人死亡通知时不更新数量显示,由GameManager统一管理
- }
-
- // 直接通过事件总线发送ENEMY_KILLED事件,避免通过GamePause的双重调用
- const eventBus = EventBus.getInstance();
- eventBus.emit('ENEMY_KILLED');
- }
- /**
- * 加载敌人骨骼动画
- */
- private loadEnemyAnimation(enemyNode: Node, enemyConfig: EnemyConfig) {
- let spinePath: string | undefined = enemyConfig.visualConfig?.spritePrefab;
- if (!spinePath) return;
- if (spinePath.startsWith('@EnemyAni')) {
- spinePath = spinePath.replace('@EnemyAni', 'Animation/EnemyAni');
- }
- if (spinePath.startsWith('@')) {
- spinePath = spinePath.substring(1);
- }
- resources.load(spinePath, sp.SkeletonData, (err, skeletonData) => {
- if (err) {
- console.warn(`加载敌人Spine动画失败: ${spinePath}`, err);
- return;
- }
- let skeleton = enemyNode.getComponent(sp.Skeleton);
- if (!skeleton) {
- skeleton = enemyNode.addComponent(sp.Skeleton);
- }
- skeleton.skeletonData = skeletonData;
- const anims = enemyConfig.visualConfig.animations;
- const walkName = anims?.walk ?? 'walk';
- const idleName = anims?.idle ?? 'idle';
- if (skeleton.findAnimation(walkName)) {
- skeleton.setAnimation(0, walkName, true);
- } else if (skeleton.findAnimation(idleName)) {
- skeleton.setAnimation(0, idleName, true);
- } else {
- console.warn(`[EnemyController] 未找到合适的动画,walk: ${walkName}, idle: ${idleName}`);
- }
- });
- }
- // 更新敌人数量显示
- public updateEnemyCountLabel(killedCount?: number) {
- if (!this.enemyCountLabelNode) {
- console.warn('[EnemyController] enemyCountLabelNode 未找到,无法更新敌人数量显示');
- return;
- }
- const label = this.enemyCountLabelNode.getComponent(Label);
- if (label) {
- // 计算剩余敌人数量:总数 - 击杀数量
- let remaining: number;
- if (killedCount !== undefined) {
- // 使用传入的击杀数量计算剩余数量
- remaining = Math.max(0, this.currentWaveTotalEnemies - killedCount);
- } else {
- // 如果没有传入击杀数量,则显示当前波次总敌人数(初始状态)
- remaining = this.currentWaveTotalEnemies;
- }
- label.string = remaining.toString();
- } else {
- console.warn('[EnemyController] enemyCountLabelNode 上未找到 Label 组件');
- }
- }
- public startWave(waveNum: number, totalWaves: number, totalEnemies: number, waveEnemyConfigs?: any[]) {
- this.currentWave = waveNum;
- this.totalWaves = totalWaves;
- this.currentWaveTotalEnemies = totalEnemies;
- this.currentWaveEnemiesSpawned = 0; // 重置已生成敌人计数器
- this.currentWaveEnemyConfigs = waveEnemyConfigs || []; // 存储当前波次的敌人配置
- // 移除EnemyController内部的击杀计数重置,统一由GameManager管理
- // this.currentWaveEnemiesKilled = 0;
-
- console.log(`[EnemyController] 开始波次 ${waveNum}/${totalWaves},需要生成 ${totalEnemies} 个敌人`);
- console.log(`[EnemyController] 波次敌人配置:`, this.currentWaveEnemyConfigs);
-
- this.updateWaveLabel();
- this.updateEnemyCountLabel();
- // 移除startWaveUI的隐藏,因为现在使用Toast预制体
- // if (this.startWaveUI) this.startWaveUI.active = false;
- }
- private updateWaveLabel() {
- if (!this.waveNumberLabelNode) {
- console.warn('[EnemyController] waveNumberLabelNode 未找到,无法更新波次标签');
- return;
- }
- const label = this.waveNumberLabelNode.getComponent(Label);
- if (label) {
- const newText = `${this.currentWave}/${this.totalWaves}`;
- label.string = newText;
- } else {
- console.warn('[EnemyController] waveNumberLabelNode 上未找到 Label 组件');
- }
- }
- /** 显示每波开始提示,随后开启敌人生成 */
- public showStartWavePromptUI(duration: number = 2) {
- // 通过事件系统检查游戏是否已经结束
- let gameOver = false;
- EventBus.getInstance().emit(GameEvents.GAME_CHECK_OVER, (isOver: boolean) => {
- gameOver = isOver;
- });
-
- if (gameOver) {
- return;
- }
-
- // 使用事件机制显示Toast
- const toastText = `第${this.currentWave}波敌人来袭!`;
- EventBus.getInstance().emit(GameEvents.SHOW_TOAST, {
- message: toastText,
- duration: duration
- });
- // 暂停生成(确保未重复)
- this.pauseSpawning();
-
- if (duration > 0) {
- this.scheduleOnce(() => {
- // 再次通过事件系统检查游戏是否已经结束
- let gameOverCheck = false;
- EventBus.getInstance().emit(GameEvents.GAME_CHECK_OVER, (isOver: boolean) => {
- gameOverCheck = isOver;
- });
-
- if (gameOverCheck) {
- return;
- }
-
- // 真正开始/恢复生成敌人
- this.startGame();
- }, duration);
- } else {
- // 立即开始游戏
- this.startGame();
- }
- }
- /**
- * 重置到初始状态
- * 用于游戏重新开始时重置所有敌人相关状态
- */
- public resetToInitialState(): void {
- // 停止游戏并清理所有敌人
- this.stopGame(true);
-
- // 重置波次信息
- this.currentWave = 1;
- this.totalWaves = 1;
- this.currentWaveTotalEnemies = 0;
- this.currentWaveEnemiesKilled = 0;
- this.currentWaveEnemiesSpawned = 0;
- this.currentWaveEnemyConfigs = [];
-
- // 重置血量倍率
- this.currentHealthMultiplier = 1.0;
-
- // 清空暂停状态
- this.pausedEnemyStates.clear();
-
- // 重置UI显示
- this.updateEnemyCountLabel();
- this.updateWaveLabel();
- }
- /**
- * 处理更新敌人计数事件
- */
- private onUpdateEnemyCountEvent(killedCount: number) {
- this.updateEnemyCountLabel(killedCount);
- }
- /**
- * 处理启动波次事件
- */
- private onStartWaveEvent(data: { wave: number; totalWaves: number; enemyCount: number; waveEnemyConfigs: any[] }) {
- this.startWave(data.wave, data.totalWaves, data.enemyCount, data.waveEnemyConfigs);
- }
- /**
- * 处理启动游戏事件
- */
- private onStartGameEvent() {
- this.startGame();
- }
- /**
- * 处理显示波次提示事件
- */
- private onShowStartWavePromptEvent() {
- this.showStartWavePromptUI();
- }
- onDestroy() {
- // 清理事件监听
- const eventBus = EventBus.getInstance();
- eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
- eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
- eventBus.off(GameEvents.GAME_SUCCESS, this.onGameEndEvent, this);
- eventBus.off(GameEvents.GAME_DEFEAT, this.onGameEndEvent, this);
- eventBus.off(GameEvents.CLEAR_ALL_GAME_OBJECTS, this.onClearAllGameObjectsEvent, this);
- eventBus.off(GameEvents.RESET_ENEMY_CONTROLLER, this.onResetEnemyControllerEvent, this);
-
- // 清理新增的事件监听
- eventBus.off(GameEvents.ENEMY_UPDATE_COUNT, this.onUpdateEnemyCountEvent, this);
- eventBus.off(GameEvents.ENEMY_START_WAVE, this.onStartWaveEvent, this);
- eventBus.off(GameEvents.ENEMY_START_GAME, this.onStartGameEvent, this);
- eventBus.off(GameEvents.ENEMY_SHOW_START_WAVE_PROMPT, this.onShowStartWavePromptEvent, this);
-
- // 清空状态
- this.pausedEnemyStates.clear();
- }
- }
|