Block.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { _decorator, Component, Node, Prefab, instantiate, Vec3, director } from 'cc';
  2. import { GameManager } from './GameManager';
  3. import { Bullet } from './Bullet';
  4. const { ccclass, property } = _decorator;
  5. @ccclass('Block')
  6. export class Block extends Component {
  7. @property(Prefab)
  8. bulletPrefab: Prefab = null;
  9. @property
  10. cooldownTime: number = 0.5;
  11. private _canFire: boolean = true;
  12. private _gameManager: GameManager = null;
  13. start() {
  14. // 获取游戏管理器
  15. this._gameManager = director.getScene().getComponentInChildren(GameManager);
  16. }
  17. fireBullet() {
  18. if (!this._canFire || !this.bulletPrefab) return;
  19. // 设置冷却时间
  20. this._canFire = false;
  21. this.scheduleOnce(() => {
  22. this._canFire = true;
  23. }, this.cooldownTime);
  24. // 创建子弹
  25. const bullet = instantiate(this.bulletPrefab);
  26. this.node.parent.addChild(bullet);
  27. // 设置子弹位置
  28. bullet.setPosition(this.node.position.clone());
  29. // 获取最近的敌人
  30. const enemies = this._gameManager.getEnemies();
  31. if (enemies && enemies.length > 0) {
  32. // 找到最近的敌人
  33. let nearestEnemy = null;
  34. let minDistance = Infinity;
  35. for (const enemy of enemies) {
  36. const distance = Vec3.distance(this.node.position, enemy.position);
  37. if (distance < minDistance) {
  38. minDistance = distance;
  39. nearestEnemy = enemy;
  40. }
  41. }
  42. // 设置子弹目标
  43. if (nearestEnemy) {
  44. const bulletComp = bullet.getComponent(Bullet);
  45. if (bulletComp) {
  46. bulletComp.setTarget(nearestEnemy);
  47. }
  48. }
  49. }
  50. }
  51. }