I am trying to create a scene using p5.js that creates many different objects in 3d space. It works fine for a small number of objects but slows down really badly for thousands of objects. The objects and their relative positions will remain the same so I was wondering if it's possible to render once and then only rotate the view angle or control with the mouse without having to draw every single object again for every single draw iteration. I have tired noloop and creating the objects outside the draw loop and the perspective change within the draw loop but the scene remains static. Many thanks in advance!
var Sz = 300;
var N = 1000;
var x = [];
var y = [];
var z = [];
// noprotect
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
background(0);
for (var i = 0; i < N; i++) {
x[i] = random(-Sz, Sz);
y[i] = random(-Sz, Sz);
z[i] = random(-Sz, Sz);
}
}
function draw() {
background(0, 0, 0);
//translate(0,0,-100);
rotateY(frameCount * 0.01);
rotateX(frameCount * 0.01);
rotateZ(frameCount * 0.01);
orbitControl();
for (var i = 0; i < N; i++) {
push();
translate(x[i], y[i], z[i]);
R = 255 * abs(x[i] / max(x));
G = 255 * abs(y[i] / max(y));
B = 255 * abs(z[i] / max(z));
stroke(R, G, B);
sphere(Sz / 50, 8);
pop();
}
}
You can start looking into Three.js or other WebGL libraries if you need this kind of control or optimization.