xxxxxxxxxx
let Lx, Ly, Lz;
let N = 500;
let cubes = [];
let msx, msy;
let time; //time
let dt = 0.04; //time step
function setup() {
createCanvas(700, 500, WEBGL);
for (let i = 0; i < N; i++) {
let theta = random() * PI;
let phi = random() * TWO_PI;
let sx = cos(phi) * sin(theta);
let sy = sin(phi) * sin(theta);
let sz = cos(theta);
cubes[i] = new Cube(sx, sy, sz, i/N * 255, 15);
}
Lx = 500; Ly = 500; Lz = 500;
time = 0;
msx = 453;
msy = 218;
}
function draw() {
background(210);
let R = width * 2;
let phi = - PI * msx / width;
let th = - PI * msy / height;
let eyeX = R * sin(th) * cos(phi);
let eyeZ = R * sin(th) * sin(phi);
let eyeY = - R * cos(th);
camera(eyeX, eyeY, eyeZ, // eyeX, eyeY, eyeZ
Lx/2,Ly/2,Lz/2, // centerX, centerY, centerZ
0.0, 2.0, 0.0); // upX, upY, upZ
drawBoundary();
for (let i = 0; i < N; i++) {
cubes[i].update();
cubes[i].display();
}
}
class Cube {
constructor(sx0, sy0, sz0, clr0, bs) {
this.s = createVector(sx0, sy0, sz0);
this.clr = clr0;
this.boxsize = bs;
}
update() {
this.s.x += 0.5*dt*this.F().x;
this.s.y += 0.5*dt*this.F().y;
this.s.z += 0.5*dt*this.F().z;
this.s.z += 0.5*dt*this.F().z;
this.s.y += 0.5*dt*this.F().y;
this.s.x += 0.5*dt*this.F().x;
}
F() {
let r = createVector(0, 0, 0);
let h = createVector(0, 0, 0);
h.x = this.s.x + this.s.x * this.s.x;
h.y = 0.5 * (this.s.y + this.s.y * this.s.y);
h.z = 0.25 * (this.s.z + this.s.z * this.s.z);
r.x = this.s.y * h.z - this.s.z * h.y;
r.y = this.s.z * h.x - this.s.x * h.z;
r.z = this.s.x * h.y - this.s.y * h.x;
return r;
}
display() {
push();
let xd = map(this.s.y, -1, 1, 0, Lx);
let yd = map(this.s.z, -1, 1, Ly, 0);
let zd = map(this.s.x, -1, 1, 0, Lz);
translate(xd, yd, zd);
stroke(0);
strokeWeight(0.5);
fill(this.clr,100,205);
box(this.boxsize);
pop();
}
}
function drawBoundary() {
push();
translate(Lx/2, Ly/2, Lz/2);
stroke(0);
noFill();
box(Lx, Ly, Lz); // the boundary
noStroke();
fill(150);
sphere(Lx/10); // sphere at origin
strokeWeight(4);
stroke(255,0,0);
line(0,0,0,0,0,Lz/2); // x-axis(red)
stroke(0,255,0);
line(0,0,0,Lx/2,0,0); // y-axis(green)
stroke(0,0,255);
line(0,0,0,0,-Ly/2,0); // z-axis(blue)
strokeWeight(1);
pop();
}
function mouseDragged() {
msx = mouseX;
msy = mouseY;
}