I'm pretty new and learning p5.js, and I am trying to make a 3D coronavirus in p5.js with a sphere and a bunch of cylinders..
You can see my sketch here: https://editor.p5js.org/zzzzzij/sketches/frE9-37R
var sketch = function (p) {
with(p) {
let angle = 0;
p.setup = function() {
createCanvas(400, 400, WEBGL);
};
p.draw = function() {
ambientLight(255);
background(175);
noStroke();
rotateY(angle);
rotateZ(angle*0.8);
normalMaterial();
push();
rotateY(PI);
sphere(100);
pop();
push();
for (i = 0; i < 24; i ++) {
rotateZ(PI/6);
push();
translate (0, -21*5, 0*5);
rotateY(PI/18);
rotateX(0);
cylinder (6, 20);
pop();
}
for (i = 0; i < 24; i ++) {
rotateZ(PI/5);
push();
translate (0, -19*5, 9*5);
rotateY(PI/18);
rotateX(-PI/8);
cylinder (6, 20);
pop();
}
for (i = 0; i < 24; i ++) {
rotateZ(PI/4);
push();
translate (0, -15*5, 15*5);
rotateY(PI/18);
rotateX(-PI/4);
cylinder (6, 20);
pop();
}
for (i = 0; i < 24; i ++) {
rotateZ(PI/3);
push();
translate (0, -9*5, 19*5);
rotateY(PI/18);
rotateX(-PI/2.5);
cylinder (6, 20);
pop();
}
for (i = 0; i < 5; i ++) {
rotateZ(0);
push();
translate (0, 0*5, 21*5);
rotateY(0);
rotateX(-PI/2);
cylinder (6, 20);
pop();
}
for (i = 0; i < 5; i ++) {
rotateZ(0);
push();
translate (0, 0*5, -21*5);
rotateY(0);
rotateX(-PI/2);
cylinder (6, 20);
pop();
}
for (i = 0; i < 24; i ++) {
rotateZ(PI/3);
push();
translate (0, 9*5, -19*5);
rotateY(-PI/18);
rotateX(-PI/2.5);
cylinder (6, 20);
pop();
}
for (i = 0; i < 24; i ++) {
rotateZ(PI/4);
push();
translate (0, 15*5, -15*5);
rotateY(-PI/18);
rotateX(-PI/4);
cylinder (6, 20);
pop();
}
for (i = 0; i < 24; i ++) {
rotateZ(PI/5);
push();
translate (0, 19*5, -9*5);
rotateY(-PI/18);
rotateX(-PI/8);
cylinder (6, 20);
pop();
}
pop();
angle+=0.01;
};
}
};
let node = document.createElement('div');
window.document.getElementById('p5-container').appendChild(node);
new p5(sketch, node);
body {
background-color:#e9e9e9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
<div id="p5-container"></div>
Since I need every cylinder to point to a different direction, I've come up with using a bunch of for loops, doing one belt of cylinders after another spaced out along Z axis, every time the loop shrinks and rotates along X and Y a bit more.
As you can see, this has resulted for me in 7 for loops. And 3 of them just have some negative values of the other 3 to complete the ball.
I'm just wondering if there's a way to write these for loops in a nested loop? I've thought through it but just couldn't think of a solution...
Or if anyone has a better way to write these cylinder loops?
Thank you!