xxxxxxxxxx
let jetsons = function (p) {
p.preload = function () {
imgs = [];
imgs[0] = p.loadImage('_george.png');
imgs[1] = p.loadImage('_jane.png');
imgs[2] = p.loadImage('_judy.png');
imgs[3] = p.loadImage('_elroy.png');
imgs[4] = p.loadImage('_astro.png');
imgs[5] = p.loadImage('_jetsons.png');
}
p.setup = function () {
/* Let's create the "real" canvas */
let p5canvas = p.createCanvas(640, 640, p.WEBGL);
// Now create the 3D shape picker buffer
p.picker = new PickBuffer3D(p5canvas, p);
// Calc random start positions for the cubes
let dst = p.shuffle([120, 140, 170, 215, 270]);
dst.push(0);
p.cubes = [];
let s = [90, 85, 70, 40, 55, 120];
for (let i = 0; i < dst.length; i++) {
let pos = p5.Vector.random3D().mult(dst[i]);
let c = new Cube(imgs[i], pos, s[i], p);
p.cubes.push(c);
p.picker.register(c);
}
// Calc rotation angle for each cube
p.dX = []; p.dY = []; p.dZ = [];
for (let i = 0; i < p.cubes.length; i++) {
p.dX[i] = (0.001 + Math.random() * 0.009) * (Math.random() < 0.5 ? -1 : 1);
p.dY[i] = (0.001 + Math.random() * 0.009) * (Math.random() < 0.5 ? -1 : 1);
p.dZ[i] = (0.001 + Math.random() * 0.009) * (Math.random() < 0.5 ? -1 : 1);
}
/* These are just to show the canvas in the example
We can comment these two lines in production */
// p.picker.buffer().show();
// p.picker.buffer().style("display", "inline");
}
p.draw = function () {
p.picker.init();
p.background(0);
for (let i = 0; i < p.cubes.length; i++) {
p.push();
p.rotateX(p.frameCount * p.dX[1]);
p.rotateY(p.frameCount * p.dY[i]);
p.rotateZ(p.frameCount * p.dZ[i]);
p.cubes[i].draw(p.picker);
p.pop();
}
}
p.mouseClicked = function () {
for (let c of p.cubes) c.deselect();
let c = p.picker.getObject(p.mouseX, p.mouseY);
let result = p.picker.getObject(p.mouseX, p.mouseY);
if (result.hit) result.hit.select();
}
// Define class locally
class Cube {
constructor(ti, pos, size, p = p5.instance) {
this._p = p;
this._texImg = ti;
this._pos = pos.copy();
this._size = size;
this._selected = false;
}
select() {
this._selected = true;
}
deselect() {
this._selected = false;
}
draw(picker) {
this._p.push();
this._p.translate(this._pos.x, this._pos.y, this._pos.z);
this._p.texture(this._texImg);
this._selected ? this._p.stroke(255, 0, 0) : this._p.stroke(128);
this._p.strokeWeight(3);
this._p.box(this._size);
if (picker && picker.uses(this)) {
let c = picker.pickColor(this);
let b = picker.buffer();
picker.prep();
b._renderer.drawingContext.flush();
b.fill(c.r, c.g, c.b);
b.box(this._size);
b._renderer.drawingContext.flush();
}
this._pop;
}
}
}
let jetsonsSketch = new p5(jetsons);