import { _decorator, Component, Node, Prefab, instantiate, Vec3, director } from 'cc'; import { GameManager } from './GameManager'; import { Bullet } from './Bullet'; const { ccclass, property } = _decorator; @ccclass('Block') export class Block extends Component { @property(Prefab) bulletPrefab: Prefab = null; @property cooldownTime: number = 0.5; private _canFire: boolean = true; private _gameManager: GameManager = null; start() { // 获取游戏管理器 this._gameManager = director.getScene().getComponentInChildren(GameManager); } fireBullet() { if (!this._canFire || !this.bulletPrefab) return; // 设置冷却时间 this._canFire = false; this.scheduleOnce(() => { this._canFire = true; }, this.cooldownTime); // 创建子弹 const bullet = instantiate(this.bulletPrefab); this.node.parent.addChild(bullet); // 设置子弹位置 bullet.setPosition(this.node.position.clone()); // 获取最近的敌人 const enemies = this._gameManager.getEnemies(); if (enemies && enemies.length > 0) { // 找到最近的敌人 let nearestEnemy = null; let minDistance = Infinity; for (const enemy of enemies) { const distance = Vec3.distance(this.node.position, enemy.position); if (distance < minDistance) { minDistance = distance; nearestEnemy = enemy; } } // 设置子弹目标 if (nearestEnemy) { const bulletComp = bullet.getComponent(Bullet); if (bulletComp) { bulletComp.setTarget(nearestEnemy); } } } } }