RainEffect.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { _decorator, Component, Node, Vec3, view, randomRangeInt, UITransform } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('RainEffect')
  4. export class RainEffect extends Component {
  5. @property(Vec3)
  6. public speed: Vec3 = new Vec3(0, -100, 0); // 雨点下落速度
  7. @property
  8. public resetY: number = 120; // 雨点重置的Y坐标
  9. private isRaining: boolean = false;
  10. private rainDrops: Node[] = [];
  11. start() {
  12. // 获取所有雨点子节点
  13. this.rainDrops = this.node.children;
  14. // 初始化雨点位置
  15. this.resetRainDrops();
  16. this.startRain();
  17. }
  18. public startRain() {
  19. this.isRaining = true;
  20. }
  21. public stopRain() {
  22. this.isRaining = false;
  23. }
  24. public clearRain() {
  25. this.stopRain();
  26. this.resetRainDrops();
  27. }
  28. private resetRainDrops() {
  29. const _width = this.node.getComponent(UITransform).width;
  30. const _height = this.node.getComponent(UITransform).height;
  31. // 随机初始化雨点的位置
  32. for (let drop of this.rainDrops) {
  33. const randomX = randomRangeInt(-_width / 2, _width / 2);
  34. const randomY = randomRangeInt(0, _height / 2);
  35. drop.setPosition(randomX, randomY, 0);
  36. }
  37. }
  38. update(dt: number) {
  39. if (!this.isRaining) return;
  40. for (let drop of this.rainDrops) {
  41. // 更新雨点位置
  42. const position = drop.position;
  43. position.add3f(this.speed.x * dt, this.speed.y * dt, this.speed.z * dt);
  44. drop.setPosition(position);
  45. const _width = this.node.getComponent(UITransform).width;
  46. const _height = this.node.getComponent(UITransform).height;
  47. if (drop.position.y < -_height / 2) {
  48. const randomX = randomRangeInt(-_width / 2, _height / 2);
  49. drop.setPosition(randomX, this.resetY, 0);
  50. }
  51. }
  52. }
  53. protected onDestroy(): void {
  54. // this.clearRain();
  55. }
  56. }