SmokePartical1.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. export default class SmokePartical1 {
  2. range; // 粒子的分布半径
  3. center; // 粒子的分布中心
  4. life; // 粒子的存活时间,毫秒
  5. createTime; // 粒子创建时间
  6. updateTime; // 上次更新时间
  7. size; // 粒子大小
  8. opacityFactor; // 粒子透系数
  9. opacity; //粒子透明度
  10. scale; // 粒子缩放量
  11. scaleFactor; //粒子放大系数
  12. position; // 粒子位置
  13. speed; //粒子扩散速度
  14. constructor(range = 10, center = { x: 0, y: 0, z: 0 }) {
  15. this.range = range; // 粒子的分布半径
  16. this.center = center; // 粒子的分布中心
  17. this.life = 400; // 粒子的存活时间,毫秒
  18. this.createTime = Date.now(); // 粒子创建时间
  19. this.updateTime = Date.now(); // 上次更新时间
  20. this.size = 3; // 粒子大小
  21. // 粒子透明度,及系数
  22. this.opacityFactor = 0.8;
  23. this.opacity = 1 * this.opacityFactor;
  24. // 粒子放大量,及放大系数
  25. this.scaleFactor = 10.5;
  26. this.scale = (this.scaleFactor * (this.updateTime - this.createTime)) / this.life; // 初始1,到达生命周期时为3
  27. // 粒子位置
  28. this.position = {
  29. x: Math.random() * 2 * this.range + this.center.x - this.range,
  30. y: this.center.y,
  31. z: Math.random() * 2 * this.range + this.center.z - this.range,
  32. };
  33. // 水平方向的扩散
  34. let speedAround = Math.random() * 10;
  35. if (speedAround < 5) speedAround -= 5;
  36. if (speedAround > 5) speedAround += 1;
  37. // 粒子的扩散速度
  38. this.speed = {
  39. x: speedAround,
  40. y: -this.life * 14,
  41. z: speedAround,
  42. };
  43. }
  44. // 更新粒子
  45. update() {
  46. const now = Date.now();
  47. const time = now - this.updateTime;
  48. // 更新位置
  49. this.position.x += (this.speed.x * time) / 2000;
  50. this.position.y += (this.speed.y * time) / 2000;
  51. this.position.z += (this.speed.z * time) / 2000;
  52. // 计算粒子透明度
  53. this.opacity = 1 - (now - this.createTime) / this.life;
  54. this.opacity *= this.opacityFactor;
  55. if (this.opacity < 0) this.opacity = 0;
  56. // 计算放大量
  57. this.scale = this.scaleFactor * ((now - this.createTime) / this.life) + 0.01;
  58. if (this.scale > 0.01 + this.scaleFactor) this.scale = 0.01 + this.scaleFactor;
  59. // 重置更新时间
  60. this.updateTime = now;
  61. }
  62. }