I tried implementing @Metamoar 's sort code – but it doesn’t seem to work. But maybe I’m doing something wrong… Here’s my code…

```
let windowSize = 0;
let rectangles = [];
function setup() {
windowSize = windowWidth < windowHeight ? windowWidth : windowHeight;
print("windowSize: " + windowSize);
createCanvas(windowSize, windowSize, WEBGL);
let fov = PI/3.0;
let cameraZ = (height/2.0) / tan(fov/2.0);
perspective(fov, float(width)/float(height), cameraZ/2.0, cameraZ*2.0);
rectangles[ 0] = new Rectangle( 100, 100, 100, 200, 255, 0, 0, 128);
rectangles[ 1] = new Rectangle( 150, 150, 150, 200, 0, 255, 0, 128);
}
class Rectangle {
constructor( x, y, z, width, r, g, b, alpha) {
this.x = x;
this.y = y;
this.z = z;
this.width = width;
this.r = r;
this.g = g;
this.b = b;
this.alpha = alpha;
}
tick() {
fill( this.r, this.g, this.b, this.alpha);
noStroke();
translate( 0, 0, this.z);
rect( this.x, this.y, this.width);
}
}
let rr = 0;
let rrShift = 0.005;
function draw() {
rectMode(CORNER)
translate(-width/2, -height/2, -400);
ambientLight( 255, 255, 255);
normalMaterial();
background(0);
rotate(rr, [1,1,0]);
rr += rrShift;
const sortedRects = rectangles.map(rectangle => {
const point = createVector(rectangle.x, rectangle.y, rectangle.z)
return {
rectangle,
point,
// Calculate the distance from the current object to the camera
dist: point.copy().sub(0, 0, (height/2) / tan(PI/6)).dot(0,0,0),
}
})
.sort((a, b) => b.dist - a.dist)
// Trees are now sorted by distance
sortedRects.forEach(obj => obj.rectangle.tick())
}
```