import { _decorator, Component, Node, ParticleSystem2D, Vec2, RigidBody2D } from 'cc'; const { ccclass, property } = _decorator; /** * 子弹尾迹控制器 * 控制子弹的粒子系统尾迹效果 */ @ccclass('PelletTrailController') export class PelletTrailController extends Component { @property(ParticleSystem2D) particleSystem: ParticleSystem2D = null; @property(RigidBody2D) rigidBody: RigidBody2D = null; private lastVelocity: Vec2 = new Vec2(); onLoad() { // 自动获取组件引用 if (!this.particleSystem) { this.particleSystem = this.node.getComponentInChildren(ParticleSystem2D); } if (!this.rigidBody) { this.rigidBody = this.node.getComponent(RigidBody2D); } } start() { // 启动粒子系统 if (this.particleSystem) { this.particleSystem.resetSystem(); } } update(deltaTime: number) { if (!this.particleSystem || !this.rigidBody) return; // 获取当前速度 const velocity = this.rigidBody.linearVelocity; // 如果速度发生变化,更新粒子发射角度 if (!velocity.equals(this.lastVelocity)) { this.updateParticleDirection(velocity); this.lastVelocity.set(velocity); } // 根据速度调整粒子发射率 const speed = velocity.length(); if (speed > 0) { // 速度越快,尾迹越明显 this.particleSystem.emissionRate = Math.max(20, speed * 0.5); this.particleSystem.enabled = true; } else { // 静止时停止发射粒子 this.particleSystem.enabled = false; } } /** * 根据子弹移动方向更新粒子发射方向 * @param velocity 子弹速度向量 */ private updateParticleDirection(velocity: Vec2) { if (velocity.length() === 0) return; // 计算速度方向角度(弧度转角度) const angle = Math.atan2(velocity.y, velocity.x) * 180 / Math.PI; // 粒子向相反方向发射,形成尾迹效果 this.particleSystem.angle = angle + 180; // 根据速度调整粒子初始速度 const speed = velocity.length(); this.particleSystem.speed = Math.min(100, speed * 0.8); this.particleSystem.speedVar = Math.min(30, speed * 0.2); } /** * 设置尾迹颜色 * @param color 颜色值 (0-255) */ public setTrailColor(r: number, g: number, b: number, a: number = 255) { if (!this.particleSystem) return; this.particleSystem.startColor.set(r, g, b, a); // 结束颜色保持透明 this.particleSystem.endColor.set(r, g, b, 0); } /** * 启用/禁用尾迹效果 */ public setTrailEnabled(enabled: boolean) { if (this.particleSystem) { this.particleSystem.enabled = enabled; if (enabled) { this.particleSystem.resetSystem(); } } } }