xxxxxxxxxx
115
const order = 5;
let total;
let path = [];
let newPath = [];
let counter = 0;
let car;
function setup() {
createCanvas(512, 512);
N = int(pow(2, order));
total = N * N;
for (let i = 0; i < total; i++) {
path[i] = hilbert(i);
let len = width / N * 32;
path[i].mult(len);
path[i].add(len / 2, len / 2);
}
car = new Car(path[0].x, path[0].y);
}
function draw() {
background(0, 255, 0);
push();
translate(car.pos.x - width / 2, car.pos.y - height / 2);
strokeWeight(125);
noFill();
//beginShape();
for (let i = 1; i < total; i++) {
stroke(155);
line(path[i].x, path[i].y, path[i - 1].x, path[i - 1].y);
}
//endShape();
// strokeWeight(4);
// for (let i = 0; i < path.length; i++) {
// point(path[i].x, path[i].y);
// text(i, path[i].x+5, path[i].y);
// }
car.update();
pop();
push();
stroke(0);
strokeWeight(3);
fill(0, 200, 0);
rect(2 * width / 3, 0, width / 3, width / 3);
for (let i = 0; i < total; i++) {
newPath[i] = hilbert(i);
let newLen = width / N / 3;
newPath[i].mult(newLen);
newPath[i].add(newLen / 2, newLen / 2);
}
push();
translate(2 * width / 3, 0);
strokeWeight(2);
for (let i = 1; i < total; i++) {
stroke(155);
line(newPath[i].x, newPath[i].y, newPath[i - 1].x, newPath[i - 1].y);
}
let posX = map(car.pos.x, 0, 512 * 32, 0, width / 3);
let posY = map(car.pos.y, 0, 512 * 32, 0, width / 3);
stroke(255, 0, 0);
strokeWeight(4);
point(5 - posX, 5 - posY);
pop();
textSize(20);
fill(0);
noStroke();
textAlign(LEFT, TOP);
text("Use W to drive forward", 0, 0);
text("and use A/D to steer left/right.", 0, 25);
text("v1.0", 0, height - 20);
pop();
}
function hilbert(i) {
const points = [
new p5.Vector(0, 0),
new p5.Vector(0, 1),
new p5.Vector(1, 1),
new p5.Vector(1, 0)
];
let index = i & 3;
let v = points[index];
for (let j = 1; j < order; j++) {
i = i >>> 2;
index = i & 3;
let len = pow(2, j);
if (index == 0) {
let temp = v.x;
v.x = v.y;
v.y = temp;
} else if (index == 1) {
v.y += len;
} else if (index == 2) {
v.x += len;
v.y += len;
} else if (index == 3) {
let temp = len - 1 - v.x;
v.x = len - 1 - v.y;
v.y = temp;
v.x += len;
}
}
return v;
}