我开始进行一个像素模拟项目,但运行效果不佳。我该如何优化它?我相当自信问题出在涉及粒子数组的所有检查中。我正在寻找任何解决方案,以做出任何不同的事情或整体优化,不仅限于粒子数组,而是整个代码。我的目标是创建一个像素模拟 Web 应用程序,如果在生成沙子几秒钟后不能良好运行,那就失去了 Web 应用程序的意义。感谢任何帮助。
主文件:
主文件:
let alter = true;
let particles = []
function setup() {
let canvas = createCanvas(windowWidth, windowHeight);
frameRate(120);
}
var a = ['rgb(244,220,148)', 'rgb(236,211,140)', 'rgb(252,228,156)', 'rgb(252,220,149)', 'rgb(244,212,148)', 'rgb(228,204,132)', 'rgb(240,220,156)']
function sandColor() {
return color(a[Math.floor(Math.random() * a.length)]);
}
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) {
return color(get(x, y));
}
function draw() {
drect(color(37, 150, 190), 0, 0, windowWidth, windowHeight)
tw = 4;
th = 4;
for (let i = 0; i < particles.length; i++) {
particles[i].draw()
}
alter = !(alter)
if (!alter) {
for (let i = 0; i < particles.length; i++) {
if (particles[i].p == 's') {
let down = false
if (JSON.stringify(check(particles[i].x, particles[i].y + 4).levels) == '[37,150,190,255]') {
particles[i].y += 4;
down = true;
}
if (!down) {
let r = Math.floor(Math.random() * 2);
if (r == 0) {
if (JSON.stringify(check(particles[i].x - 4, particles[i].y + 4).levels) == '[37,150,190,255]') {
particles[i].y += 4;
particles[i].x -= 4;
} else {
if (JSON.stringify(check(particles[i].x + 4, particles[i].y + 4).levels) == '[37,150,190,255]') {
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 (let m = 0; m < particles.length; m++) {
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://pixsim.loganstottle202.repl.co/,如果无法使用,则代码在此处:https://replit.com/@LoganStottle202/pixsim?v=1