AutoFireWeapon.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { _decorator, Component, Prefab, instantiate, Node, Vec3, macro, find } from 'cc';
  2. import { ArcBullet } from './ArcBullet';
  3. const { ccclass, property } = _decorator;
  4. /**
  5. * AutoFireWeapon
  6. * 绑定在武器(Block001)节点上的脚本,负责定时发射子弹。
  7. */
  8. @ccclass('AutoFireWeapon')
  9. export class AutoFireWeapon extends Component {
  10. /** 将 Pellet 预制体拖到此处 */
  11. @property(Prefab)
  12. public bulletPrefab: Prefab | null = null;
  13. /** 射速:两发子弹之间的间隔(秒) */
  14. @property
  15. public fireInterval: number = 0.5;
  16. /** 子弹速度(像素/秒) */
  17. @property
  18. public bulletSpeed: number = 800;
  19. /** 子弹转向速率(0~1) */
  20. @property
  21. public rotateSpeed: number = 0.5;
  22. /** 目标敌人(可选)。不设置则在 Canvas 下查找名为 Enemy 的节点 */
  23. @property({ type: Node, tooltip: '敌人节点(如果为空,则自动在 Canvas 下查找名为 Enemy 的节点)' })
  24. public enemyNode: Node | null = null;
  25. onEnable() {
  26. // 若未指定敌人,尝试在场景中查找
  27. if (!this.enemyNode) {
  28. this.enemyNode = find('Canvas/Enemy');
  29. }
  30. // 立即发射一枚,然后按间隔循环
  31. this.schedule(this.spawnBullet.bind(this), this.fireInterval, macro.REPEAT_FOREVER, 0);
  32. }
  33. onDisable() {
  34. this.unscheduleAllCallbacks();
  35. }
  36. private spawnBullet() {
  37. if (!this.bulletPrefab) {
  38. console.warn('[AutoFireWeapon] 未设置 bulletPrefab');
  39. return;
  40. }
  41. // 实例化子弹
  42. const bullet = instantiate(this.bulletPrefab);
  43. if (!bullet) return;
  44. // 将子弹添加到场景
  45. this.node.parent?.addChild(bullet);
  46. // 将子弹世界位置设置为武器当前位置
  47. const worldPos = this.node.worldPosition;
  48. bullet.setWorldPosition(new Vec3(worldPos.x, worldPos.y, worldPos.z));
  49. // 配置 ArcBullet 组件
  50. const arcBullet = bullet.getComponent(ArcBullet) || bullet.addComponent(ArcBullet);
  51. arcBullet.moveSpeed = this.bulletSpeed;
  52. arcBullet.rotateSpeed = this.rotateSpeed;
  53. arcBullet.target = this.enemyNode;
  54. // 可根据需要设置 arcBullet.target = 某个目标节点
  55. }
  56. }