更新生命周期

时间:2016-05-11 22:50:36

标签: javascript jsfiddle

我试图弄清楚如何更新颗粒的寿命,以便它不那么僵硬,实际上可以平稳地回收,而不是在波浪中。

https://jsfiddle.net/jceisner/5rqwx26n/

function update {
 for(var i = 0; i < particles.length-25; i++){
// keep moving if still alive or still on screen
    if(particles[i].lifetime > 0 || particles[i].x < 0){
        particles[i].x -= particles[i].radius*0.5;
        particles[i].lifetime--; // must be --
} else {
    // reset particles
  particles[i].x = canvas.width;
  particles[i].lifetime = canvas.width;
  particles[i].y = Math.random()*canvas.height; //will randomize x position
  particles[i].radius;
  } 
 }
}

我缺少什么?

1 个答案:

答案 0 :(得分:1)

现在每个粒子都拥有相同的生命周期,因此所有粒子都会同时死亡。因此严格的重置。

只需将有关生命的一切都从你的小提琴中取出,并将小于if(particles[i].x < 0)改为大于if(particles[i].x > 0) ......

*少foobar版本:

因为我真的很喜欢这个想法并且有一些时间在我的手上我重写了演示,以减少foobar,使用requestAnimationFrame,使用camelCasing而不是under_scores等...:)

(function STARS() {
  "use strict";
  var canvas = document.getElementById("output");
  var context = canvas.getContext("2d");

  var time = Date.now();
  var deltaTime = 0;
  var fps = 90;

  var particles = [];

  function particle() {
    var that = {
      x: Math.random() * canvas.width,
      y: Math.random() * canvas.height,
      radius: Math.random() * 5,
      speed: Math.random() * 0.9
    };

    return that;
  }

  function particleSystem(numParticles) {
    var i = numParticles;
    while (i) {
      particles.push(particle());
      i -= 1;
    }
  }
  particleSystem(100);

  function update() {
    var i = particles.length;
    while (i) {
      i -= 1;

      if (particles[i].x > 0) {
        particles[i].x -= particles[i].radius * 0.5;
      } else {
        particles[i].x = canvas.width;
        particles[i].y = Math.random() * canvas.height;
      }
    }
  }

  function draw() {
    context.clearRect(0, 0, canvas.width, canvas.height);

    var i = particles.length;
    var par = undefined;
    while (i) {
      i -= 1;
      par = particles[i];

      context.fillStyle = "orange";
      context.beginPath();
      context.arc(par.x, par.y, par.radius, Math.PI * 2, false);
      context.stroke();
      context.fill();
    }
  }

  function gameLoop() {
    var now = Date.now();

    deltaTime += now - time;
    time = now;

    // cap deltaTime to one second to prevent freezing
    if (deltaTime > 1000) {
        deltaTime = 1000;
    }

    while (deltaTime > 1000 / fps) {
      update();

      deltaTime -= 1000 / fps;
    }

    draw();

    window.requestAnimationFrame(gameLoop);
  }
  gameLoop();
}());
<canvas id="output" width="630px" height="180px"></canvas>