Оптимізація п5.js коду для підвищення продуктивності: зменшення лагів зі збереженням візуального ефекту

Оптимізація п5.js коду для підвищення продуктивності: зменшення лагів зі збереженням візуального ефекту

7 Березня 2024 в 17:14 36

Як можна оптимізувати цей конкретний фрагмент мого коду на п5.js (використовуючи тригонометричні функції), щоб зменшити лаги, при цьому зберігаючи візуальний ефект? Отже, на моєму ноутбуці все працює нормально - у мене є MacBook Pro 2021 з 16 ГБ оперативної пам'яті, і мій код працює приблизно з 30 кадрами в секунду. Проте інші люди пробували відкривати мій код на своїх ноутбуках і стикаються з серйозними лагами, до такої міри, що деякі взагалі не можуть запустити код. Я визначив конкретний уривок свого коду, який майже подвоює лаги (якщо його видалити, я повертаюся до приблизно 60 FPS), але я не знаю, як його змінити, щоб зменшити лаги, при цьому зберігаючи візуальний ефект. Проблемний код - це розділ, позначений "жовті з'єднувачі" з рядків 98-103. Я вже пробував змінити рядки на точки, що дійсно збільшує мої FPS з 30 до 60, але, очевидно, змінює вигляд жовтих з'єднувачів. Я хочу змінити рядки на точки, а потім змінити, як кодуються точки, щоб точки все ще виглядали як рухома послідовність ліній, що з'єднують червоний та синій двокручення. Можливо, замість застосування функції sin до жовтих з'єднувачів, я міг би використовувати функцію tan або щось інше? Я не знаю, чи це взагалі можливо, але мені потрібна допомога! p5.disableFriendlyErrors = true; var si=0.1; var hi=0.1; let tenet; let words; function preload() { tenet = loadImage('proneil.jpeg'); words = loadImage('tenetword.png'); } function setup() { console.log('Move your mouse across the screen. Hold down on the "0", "9", or "8" keys on your keyboard to change up the visuals. Click and drag across the screen to change the POV.','Then try different combinations of clicking, dragging, and using your keyboard. Double click to reset. Have fun! :)'); createCanvas(1000, 600, WEBGL); camera(0, 0, (height/1.4) / tan(PI/6), 0, 0, 0, 0.15, 1, 0); perspective(1050, width / height, 100, 2000); // learned from Coding Train video: // https://www.youtube.com/watch?v=BW3D9WwalQE&list=PLRqwX-V7Uu6bPhi8sS1hHJ77n3zRO9FR_&index=6 blendMode(BLEND); } function draw() { console.log(frameRate()); //Color changing background let bg = map(noise(frameCount*0.01),0,1,-50,100) background(60-bg,0,10+bg); // Color changing code is from lines 70-73 of: // https://editor.p5js.org/EdCavett/sketches/r_JeOy-v noFill(); //White noise background for (var a=0; a<=width*2; a++) { strokeWeight(1); stroke(255,255,0); point(a-650, random(height*3)-1000); } // Edited from Coding Train video: // https://www.youtube.com/watch?v=y7sgcFhk6ZM //BACKGROUND WAVES //Continuous sin wave animation for (var x=1; x<=height+3000; x=x+5) { let twist = map(mouseX,0,1000,3*PI,PI) if (keyIsPressed===true && key==='0') { rotateY(PI); } else if(keyIsPressed===true && key==='9') { rotateY(twist/mouseY); } else { rotateY(PI*2) } // Pressing the '0' and '9' keys on the keyboard allows user to rotate the scene in different ways to create cool visuals. // https://p5js.org/reference/#/p5/keyIsPressed var j=(x+hi)/95; var z = cos(j*1.4); // Base loop from Claire // https://editor.p5js.org/clairez/sketches/7CTJFKiO- // Changed to sin() & some values changed //purple shadow strokeWeight(18); stroke(100,120,150,50); point(x-3000, z*height/-3,0); //red blue strands strokeWeight(15); stroke(200,200,0,30); point(x-2900, z*height/2,0); stroke(0,200,200,30); point(x-2800, z*height/-1.5,0); //BACKGROUND WAVES END //FOREGROUND DOUBLE HELIX START!!!! var p=(x+si)/95; var y = sin(p*1.55); noFill(); //white shadow strokeWeight(45); stroke(255,10); point(x-2900, y*height/7); stroke(255,10); point(x-2900, y*height/-8); //yellow connectors strokeWeight(1); stroke(200,200,0); line(x-2900, y,x-2900, y*height/8.5) stroke(250,200,0); line(x-2900, y*height/-8.5,x-2900, y) //purple shadow strokeWeight(35); stroke(100,0,100,150); point(x-2900, y*height/7.5); stroke(100,0,100,150); point(x-2900, y*height/-7.5); //red and blue strands strokeWeight(30); stroke(255,0,0,150); point(x-2900, y*height/7); stroke(0,0,255,150); point(x-2900, y*height/-8); if (mouseIsPressed) { rotateY(PI); x--; si+=0.04; hi+=0.02; } else { let zoom1 = map(mouseY,0,600,1050,1049.9); perspective(zoom1, 1.6, 100, 2000); } // Changes animation speed and removes effect of zoom1 when mouse is pressed down. //FOREGROUND DOUBLE HELIX END!!!! if(keyIsPressed===true && key==='8') { push(); blendMode(LIGHTEST); // https://p5js.org/reference/#/p5/blendMode image(tenet,random(-140,-160),random(-110,-90),190,190); blendMode(BLEND); let shade = map(mouseX,0,1000,10,50) tint(255,shade); image(tenet,random(-145,-155),random(-105,-95),190,190); image(words,random(-15,-20),random(-100,-95),500,700); pop(); //Photo and text with blend effect appear when "8" key is held down. } } si++; hi+=3; // Sets animation speed } function mouseDragged() { let zoom = map(mouseX,0,1000,1050,1050.5) camera(0, 0, (height/1.4) / tan(PI/6), mouseX/8, 0, 0, 0.15, 1, 0); perspective(zoom, width / height, 100, 1000); } // Changes camera perspective when mouse is dragged on the x-axis. function doubleClicked() { camera(0, 0, (height/1.4) / tan(PI/6), 0, 0, 0, 0.15, 1, 0); perspective(1050, width / height, 100, 1000); } // Resets camera perspective to normal when mouse is double clicked.