3d Tunnel ⚙️

Attempt to understand this projection thing a bit.

twitter.com/mknol

Log in to post a comment.

// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(.68);

const turtle = new Turtle();

const posX = 7; // min=-100, max=100, step=1
const posY = 30; // min=-100, max=100, step=1
const posZ = -20; // min=-100, max=100, step=1
const panX = -35; // min=-100, max=100, step=1
const panY = -20; // min=-100, max=100, step=1
const panZ = 0; // min=-100, max=100, step=1
const rotateX = 0.2; // min=-6, max=6, step=0.01

const camera = {
    rotationX: rotateX, // todo: x,y,z
    pos: [posX,posY,posZ],
    pan: [panX,panY,panZ],
}

// The walk function will be called until it returns false.
function walk(i) {
    for(let c=0; c<40; c++) {
        const z = (-10 + c) * 14;
        const plane = [
            [-15,-15, z],
            [-15, 15, z],
            [ 15, 15, z],
            [ 15,-15, z],
        ];
        drawPlane(plane);
    }
    
    return false;
}

function drawPlane(segments) {
    turtle.penup();
    for(let s=0, l=segments.length; s<=l; s++) {
        if (s==1) turtle.pendown();
        
        let segment = segments[s % l];
        segment = add(segment, camera.pos);
        segment = rotX(camera.rotationX, segment);
        segment = project(segment);
        segment = add(segment, camera.pan);
        turtle.goto(segment);
    }
}

/**************************************************/

// some functions from https://turtletoy.net/turtle/2dc4806767
function project(p) {
    p[2] += 180.;
    return [p[0]/p[2]*180., p[1]/p[2]*180., p[2]];
}
const cos = Math.cos;
const sin = Math.sin;
const scale = (p,scale) => [p[0]*scale, p[1]*scale, p[2]*scale];
const add = (a,b) => [a[0]+b[0], a[1]+b[1], a[2]+b[2]];
const sub = (a,b) => [a[0]-b[0], a[1]-b[1], a[2]-b[2]];
const cross = (a,b) => [
    a[1]*b[2]-b[1]*a[2],
    a[2]*b[0]-b[2]*a[0],
    a[0]*b[1]-b[0]*a[1]
];
const rotX = (ph,v) => [v[0], v[1]*cos(ph)+v[2]*sin(ph), v[2]*cos(ph)-v[1]*sin(ph)];