import { _decorator, Component, Node, Vec3, view, randomRangeInt, UITransform } from 'cc'; const { ccclass, property } = _decorator; @ccclass('RainEffect') export class RainEffect extends Component { @property(Vec3) public speed: Vec3 = new Vec3(0, -100, 0); // 雨点下落速度 @property public resetY: number = 120; // 雨点重置的Y坐标 private isRaining: boolean = false; private rainDrops: Node[] = []; start() { // 获取所有雨点子节点 this.rainDrops = this.node.children; // 初始化雨点位置 this.resetRainDrops(); this.startRain(); } public startRain() { this.isRaining = true; } public stopRain() { this.isRaining = false; } public clearRain() { this.stopRain(); this.resetRainDrops(); } private resetRainDrops() { const _width = this.node.getComponent(UITransform).width; const _height = this.node.getComponent(UITransform).height; // 随机初始化雨点的位置 for (let drop of this.rainDrops) { const randomX = randomRangeInt(-_width / 2, _width / 2); const randomY = randomRangeInt(0, _height / 2); drop.setPosition(randomX, randomY, 0); } } update(dt: number) { if (!this.isRaining) return; for (let drop of this.rainDrops) { // 更新雨点位置 const position = drop.position; position.add3f(this.speed.x * dt, this.speed.y * dt, this.speed.z * dt); drop.setPosition(position); const _width = this.node.getComponent(UITransform).width; const _height = this.node.getComponent(UITransform).height; if (drop.position.y < -_height / 2) { const randomX = randomRangeInt(-_width / 2, _height / 2); drop.setPosition(randomX, this.resetY, 0); } } } protected onDestroy(): void { // this.clearRain(); } }