| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- import { _decorator, Component, Prefab, instantiate, Node, Vec3, macro, find } from 'cc';
- import { ArcBullet } from './ArcBullet';
- const { ccclass, property } = _decorator;
- /**
- * AutoFireWeapon
- * 绑定在武器(Block001)节点上的脚本,负责定时发射子弹。
- */
- @ccclass('AutoFireWeapon')
- export class AutoFireWeapon extends Component {
- /** 将 Pellet 预制体拖到此处 */
- @property(Prefab)
- public bulletPrefab: Prefab | null = null;
- /** 射速:两发子弹之间的间隔(秒) */
- @property
- public fireInterval: number = 0.5;
- /** 子弹速度(像素/秒) */
- @property
- public bulletSpeed: number = 800;
- /** 子弹转向速率(0~1) */
- @property
- public rotateSpeed: number = 0.5;
- /** 目标敌人(可选)。不设置则在 Canvas 下查找名为 Enemy 的节点 */
- @property({ type: Node, tooltip: '敌人节点(如果为空,则自动在 Canvas 下查找名为 Enemy 的节点)' })
- public enemyNode: Node | null = null;
- onEnable() {
- // 若未指定敌人,尝试在场景中查找
- if (!this.enemyNode) {
- this.enemyNode = find('Canvas/Enemy');
- }
- // 立即发射一枚,然后按间隔循环
- this.schedule(this.spawnBullet.bind(this), this.fireInterval, macro.REPEAT_FOREVER, 0);
- }
- onDisable() {
- this.unscheduleAllCallbacks();
- }
- private spawnBullet() {
- if (!this.bulletPrefab) {
- console.warn('[AutoFireWeapon] 未设置 bulletPrefab');
- return;
- }
- // 实例化子弹
- const bullet = instantiate(this.bulletPrefab);
- if (!bullet) return;
- // 将子弹添加到场景
- this.node.parent?.addChild(bullet);
- // 将子弹世界位置设置为武器当前位置
- const worldPos = this.node.worldPosition;
- bullet.setWorldPosition(new Vec3(worldPos.x, worldPos.y, worldPos.z));
- // 配置 ArcBullet 组件
- const arcBullet = bullet.getComponent(ArcBullet) || bullet.addComponent(ArcBullet);
- arcBullet.moveSpeed = this.bulletSpeed;
- arcBullet.rotateSpeed = this.rotateSpeed;
- arcBullet.target = this.enemyNode;
- // 可根据需要设置 arcBullet.target = 某个目标节点
- }
- }
|