3d Tunnel ⚙️

Attempt to understand this projection thing a bit.

twitter.com/mknol

Created by markknol on 2018/12/3
376
0

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 camera = {
    rotationX: 0.2, // todo: x,y,z
    pos: [7, 30, 0],
    pan: [-35, -20, 0],
}

// 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)];