我正在制造一个粒子引擎,可以产生新的爆炸,同时保持粒子从以前的活跃(直到他们绝望)。
代码本身运行良好,但在游戏中,两次或更多的活跃爆炸会引起口吃,特别是在几年前的笔记本电脑上。我想知道我的代码是否存在固有的低效,或者使用的任何编码实践都是不好的。
在下面的代码片段中,您可以单击画布元素中的任何位置来查看粒子效果。如果有什么不清楚的地方请告诉我。
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var explosions = [];
var mouseX;
var mouseY;
canvas.addEventListener('mousemove', setMouse, false);
canvas.addEventListener('click', function() {
explosions.push(new explosion(mouseX, mouseY));
}, false);
function loop() {
ctx.clearRect(0, 0, 500, 500);
drawExplosion();
requestAnimationFrame(loop);
}
loop();
function drawExplosion() {
if (explosions.length === 0) {
return;
}
for (let i = 0; i < explosions.length; i++) {
const explosion = explosions[i];
const projectiles = explosion.projectiles;
if (projectiles.length === 0) {
explosions.splice(i, 1);
return;
}
const projectilesRemove = projectiles.slice();
for (let ii = 0; ii < projectiles.length; ii++) {
const projectile = projectiles[ii];
// remove projectile if radius is below 0
if (projectile.radius < 0) {
projectilesRemove.splice(ii, 1);
continue;
}
// draw
ctx.beginPath();
ctx.arc(projectile.x, projectile.y, projectile.radius, Math.PI * 2, 0, false);
ctx.closePath();
ctx.fillStyle = 'hsl(' + projectile.h + ',' + projectile.s + '%,' + projectile.l + '%)';
ctx.fill();
// update
projectile.x -= projectile.vx * 1;
projectile.y -= projectile.vy * 1;
projectile.radius -= 0.02;
// collisions
if (projectile.x > 500) {
projectile.x = 500;
projectile.vx *= -1;
}
if (projectile.x < 0) {
projectile.x = 0;
projectile.vx *= -1;
}
if (projectile.y > 500) {
projectile.y = 500;
projectile.vy *= -1;
}
if (projectile.y < 0) {
projectile.y = 0;
projectile.vy *= -1;
}
}
explosion.projectiles = projectilesRemove;
}
}
function explosion(x, y) {
this.projectiles = [];
for (let i = 0; i < 100; i++) {
this.projectiles.push(
new projectile(x, y)
);
}
}
function projectile(x, y) {
this.x = x;
this.y = y;
this.radius = 2 + Math.random() * 4;
this.vx = -10 + Math.random() * 20;
this.vy = -10 + Math.random() * 20;
this.h = 200;
this.s = Math.floor((Math.random() * 100) + 70);
this.l = Math.floor((Math.random() * 70) + 30);
}
function setMouse(e) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}发布于 2018-10-29 02:12:48
https://codereview.stackexchange.com/questions/206451
复制相似问题