像素/沙箱模拟器优化



我已经在这个项目上工作了几天,它是一个像素模拟器,我现在唯一的元素是沙子。我正在对沙子作为其他元素基础的物理特性进行微调。不过,我注意到了一些事情,在放置沙子一段时间后,程序开始显著减慢,我正在寻找任何改进或可以在代码中做的不同事情,以使它更好地运行。感谢您的帮助。谢谢

主文件的代码:

let alter = true;
particles = []
function setup() {
let canvas = createCanvas(windowWidth, windowHeight);
frameRate(120);
}
function sandColor() {
r = Math.floor(Math.random() * (255 - 230 + 1) + 230)
g = Math.floor(Math.random() * (230 - 200 + 1) + 230)
b = Math.floor(Math.random() * (150 - 130 + 1) + 130)
return color(r, g, b)
}
function drect(c, x, y, l, w) {
noStroke();
fill(c);
rect(x, y, l, w);
}
class Particle {
constructor(p, c, x, y, s) {
this.p = p;
this.c = c;
this.x = x;
this.y = y;
this.s = s;
}
draw() {
drect(this.c, this.x, this.y, this.s, this.s);
}
}
function check(x, y) {
found = false;
let p;
for (i in particles) {
if (particles[i].x == x && particles[i].y == y) {
found = true;
p = particles[i].p;
}
}
if (found) {
return [found, p]
} else {
return [found];
}
}
function draw() {
drect(color(37, 150, 190), 0, 0, windowWidth, windowHeight)
tw = 4;
th = 4;
for (var i in particles) {
particles[i].draw()
}
alter = !(alter)
if (!alter) {
for (i in particles) {
if (particles[i].p == 's') {
let down = false
if (!check(particles[i].x, particles[i].y + 4)[0]) {
particles[i].y += 4;
down = true;
}
if (!down) {
let r = Math.floor(Math.random() * 2) + 1;
if (r == 1) {
if (!check(particles[i].x - 4, particles[i].y + 4)) {
particles[i].y += 4;
particles[i].x -= 4;
} else {
if (!check(particles[i].x + 4, particles[i].y + 4)) {
particles[i].y += 4;
particles[i].x += 4;
}
}
}
}
}
}
if (mouseIsPressed) {
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 6; j++) {
let p = 's'
let c = sandColor()
let x = (Math.floor(mouseX / tw)) * tw + (i * 4) - 9;
let y = (Math.floor(mouseY / th)) * th + (j * 4) - 9;
let s = 4;
let sand = new Particle(p, c, x, y, s)
let d = true;
for (var m in particles) {
if (particles[m].x == x && particles[m].y == y && particles[m].p == "s") {
d = false;
}
}
if (d) {
drect(c, x, y, s, s)
particles.push(sand)
}
}
}
}
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
document.addEventListener('contextmenu', event => event.preventDefault());
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.min.js"></script>

托管示例和完整源代码如下:https://replit.com/@LoganStottle202/pixsim?v=1

正常的for()循环比for( in )循环快6到11倍

这是您当前的代码:

function check(x, y) {
found = false;
let p;
for (i in particles) {
if (particles[i].x == x && particles[i].y == y) {
found = true;
p = particles[i].p;
}
}
if (found) {
return [found, p] 
} else {
return [found];
}
}

我也会删除一些不必要的变量(它们可以用返回来代替(

我要更改的另一件事是,在javascript中,如果从for()循环或if()语句中删除方括号,它将只执行下一个语句。这是你可以在这里做的事情

我会这样做:

function check(x, y) {
for (let i = 0; i < particles.length; i++)
if (particles[i].x == x && particles[i].y == y)
return [true, particles[i].p];
return [false];
}

优点:

  • 更快
  • 易于阅读
  • 更少的文本,更小的文件

最新更新