我正在尝试找出如何更新粒子的生命周期,这样它就不会那么僵化,并且实际上可以顺利地回收,而不是波浪式的。
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;
}
}
}
我错过了什么???
最佳答案
现在每个粒子都具有相同的生命周期,因此所有粒子都会同时死亡。因此,硬性重置。
只需将有关生命周期的所有内容从你的 fiddle 中取出,并更改小于 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>
关于javascript - 更新生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37174537/