PelletTrailController.ts 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { _decorator, Component, Node, ParticleSystem2D, Vec2, RigidBody2D } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. /**
  4. * 子弹尾迹控制器
  5. * 控制子弹的粒子系统尾迹效果
  6. */
  7. @ccclass('PelletTrailController')
  8. export class PelletTrailController extends Component {
  9. @property(ParticleSystem2D)
  10. particleSystem: ParticleSystem2D = null;
  11. @property(RigidBody2D)
  12. rigidBody: RigidBody2D = null;
  13. private lastVelocity: Vec2 = new Vec2();
  14. onLoad() {
  15. // 自动获取组件引用
  16. if (!this.particleSystem) {
  17. this.particleSystem = this.node.getComponentInChildren(ParticleSystem2D);
  18. }
  19. if (!this.rigidBody) {
  20. this.rigidBody = this.node.getComponent(RigidBody2D);
  21. }
  22. }
  23. start() {
  24. // 启动粒子系统
  25. if (this.particleSystem) {
  26. this.particleSystem.resetSystem();
  27. }
  28. }
  29. update(deltaTime: number) {
  30. if (!this.particleSystem || !this.rigidBody) return;
  31. // 获取当前速度
  32. const velocity = this.rigidBody.linearVelocity;
  33. // 如果速度发生变化,更新粒子发射角度
  34. if (!velocity.equals(this.lastVelocity)) {
  35. this.updateParticleDirection(velocity);
  36. this.lastVelocity.set(velocity);
  37. }
  38. // 根据速度调整粒子发射率
  39. const speed = velocity.length();
  40. if (speed > 0) {
  41. // 速度越快,尾迹越明显
  42. this.particleSystem.emissionRate = Math.max(20, speed * 0.5);
  43. this.particleSystem.enabled = true;
  44. } else {
  45. // 静止时停止发射粒子
  46. this.particleSystem.enabled = false;
  47. }
  48. }
  49. /**
  50. * 根据子弹移动方向更新粒子发射方向
  51. * @param velocity 子弹速度向量
  52. */
  53. private updateParticleDirection(velocity: Vec2) {
  54. if (velocity.length() === 0) return;
  55. // 计算速度方向角度(弧度转角度)
  56. const angle = Math.atan2(velocity.y, velocity.x) * 180 / Math.PI;
  57. // 粒子向相反方向发射,形成尾迹效果
  58. this.particleSystem.angle = angle + 180;
  59. // 根据速度调整粒子初始速度
  60. const speed = velocity.length();
  61. this.particleSystem.speed = Math.min(100, speed * 0.8);
  62. this.particleSystem.speedVar = Math.min(30, speed * 0.2);
  63. }
  64. /**
  65. * 设置尾迹颜色
  66. * @param color 颜色值 (0-255)
  67. */
  68. public setTrailColor(r: number, g: number, b: number, a: number = 255) {
  69. if (!this.particleSystem) return;
  70. this.particleSystem.startColor.set(r, g, b, a);
  71. // 结束颜色保持透明
  72. this.particleSystem.endColor.set(r, g, b, 0);
  73. }
  74. /**
  75. * 启用/禁用尾迹效果
  76. */
  77. public setTrailEnabled(enabled: boolean) {
  78. if (this.particleSystem) {
  79. this.particleSystem.enabled = enabled;
  80. if (enabled) {
  81. this.particleSystem.resetSystem();
  82. }
  83. }
  84. }
  85. }