I've started on a pixel sim project and it doesn't run well. What can I do to optimize it? I'm fairly confident that the issue is in all the checks that are done involving the particles array. I'm looking for any solution, to do anything different, or any optimizations in general, not just about the particles array but throughout the whole code. My goal for this project is to create a pixel sim web app, and if it can't run well after a few seconds of spawning sand, it defeats the purpose of a web app. Any help is appreciated.
Main file:
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>
Hosted example: https://pixsim.loganstottle202.repl.co/ and if that doesn't work the code is here: https://replit.com/@LoganStottle202/pixsim?v=1