Hello! Im trying to learn about perspective using code and create my own drawing system.
I have this piece of code and my problem is that i dont know how to sort the sides of the cube to draw them correctly according to the vanish point (in what order should i draw the sides). My intuition says that i need to establish a viewer point of view and sort every side by the distance. But i dont know how to emulate that viewer point in perspective.
Thanks!
let persp;
let cube
function setup() {
createCanvas(400, 400);
persp = new Perspective_class(createVector(width / 2 - 100, height / 2));
cube = new Cube(0,createVector(width/2,100),100,200,0.2)
}
function draw() {
background(220);
stroke(0);
line(0, persp.vanish.y, width, persp.vanish.y);
ellipse(persp.vanish.x, persp.vanish.y, 10);
cube.draw()
}
class Perspective_class {
constructor(pos) {
this.vanish = pos;
}
}
class Polygon {
constructor(index, points) {
this.index = index;
this.points = points;
console.log(this.points)
}
draw() {
fill(random(240, 255), 240, random(255, 250));
stroke(0);
beginShape();
for (let i = 0; i < 4; i++) {
vertex(this.points[i].x, this.points[i].y);
}
endShape(CLOSE);
}
}
class Cube {
constructor(index, position, w, h, l) {
this.position = position;
this.w = w;
this.h = h;
this.l = l;
this.others = [];
this.index = index;
this.polygons = []
this.points = [
createVector(this.position.x, this.position.y),
createVector(this.position.x, this.position.y + this.h),
createVector(this.position.x + this.w, this.position.y + this.h),
createVector(this.position.x + this.w, this.position.y),
];
this.generateSides()
}
generateSides() {
this.depth(this.points)
this.back();
this.front();
this.left();
this.right();
this.bottom();
this.top();
}
back() {
this.polygons.push(
new Polygon(0, [
this.others[0],
this.others[1],
this.others[2],
this.others[3],
])
);
}
front() {
this.polygons.push(
new Polygon(1, [
this.points[0],
this.points[1],
this.points[2],
this.points[3],
])
);
}
left() {
this.polygons.push(
new Polygon(2, [
this.others[0],
this.others[1],
this.points[1],
this.points[0],
])
);
}
right() {
this.polygons.push(
new Polygon(3, [
this.points[3],
this.points[2],
this.others[2],
this.others[3],
])
);
}
top() {
this.polygons.push(
new Polygon(4, [
this.others[0],
this.points[0],
this.points[3],
this.others[3],
])
);
}
bottom() {
this.polygons.push(
new Polygon(5, [
this.points[1],
this.others[1],
this.others[2],
this.points[2],
])
);
}
depth(points) {
for (let p of points) {
let a = lerpVector(p, persp.vanish, this.l);
this.others.push(a);
}
}
draw() {
for (let poly of this.polygons) {
poly.draw();
}
}
}
function lerpVector(a, b, f) {
let aa = lerp(a.x, b.x, f);
let bb = lerp(a.y, b.y, f);
return createVector(aa, bb);
}