xxxxxxxxxx
119
let nodes = [];
let springs = [];
let selected = 0;
const rows = 30;
const cols = 30;
const g = 0.001;
const k = 0.0001;
const delta_t = 0.5;
let cat;
function preload() {
cat = loadImage('cat.jpg');
}
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
// Setting up a grid of nodes
const w = windowWidth*0.8;
const h = windowHeight*0.2;
// const left_offset = (windowWidth - w)/2;
const left_offset = -w/2;
// const top_offset = (windowHeight - h)/2;
const top_offset = -h*2;
const dx = w/(cols - 1);
const dy = h/(rows - 1);
for(let i = 0; i < rows; ++i) {
for(let j = 0; j < cols; ++j) {
let vel = createVector(0, 0);
const mass = 0.5;
let pos = createVector(left_offset + j*dx, top_offset+ i*dy);
let fixed = (i == 0);
nodes.push(new Node(pos, vel, mass, fixed = fixed))
}
}
// Connect every adj. nodes with springs
// Horizontal connections
for(let i = 0; i < rows; ++i) {
for(let j = 0; j < cols-1; ++j) {
springs.push(new Spring(nodes[i*rows + j], nodes[i*rows + j+1], k));
}
}
// Vertical connections
for(let j = 0; j < cols; ++j) {
for(let i = 0; i < rows-1; ++i) {
springs.push(new Spring(nodes[i*rows + j], nodes[(i+1)*rows + j], k));
}
}
// Diagonal connections
for(let j = 0; j < cols-1; ++j) {
for(let i = 0; i < rows-1; ++i) {
springs.push(new Spring(nodes[i*rows + j], nodes[(i+1)*rows + j+1], k));
}
}
for(let j = 1; j < cols; ++j) {
for(let i = 0; i < rows-1; ++i) {
springs.push(new Spring(nodes[i*rows + j], nodes[(i+1)*rows + j-1], k));
}
}
}
function draw() {
background(220);
// springs.forEach((spring) => spring.show())
nodes.forEach((node) => {
node.update();
// node.show();
}
);
//
nodes.forEach((node) => {
node.vel.mult(0.999);
})
textureMode(NORMAL);
for(let i = 0; i < rows-1; ++i) {
texture(cat);
rotateZ(PI/2);
beginShape(TRIANGLE_STRIP);
for(let j = 0; j < cols; ++j) {
let N_1 = nodes[i*rows + j];
let N_2 = nodes[(i+1)*rows + j];
vertex(N_1.pos.x, N_1.pos.y, i/(rows-1), j/(cols-1));
vertex(N_2.pos.x, N_2.pos.y, (i+1)/(rows-1), j/(cols-1));
}
endShape();
}
}
function mousePressed() {
// Find closest node
let min_distance = 100000;
let closest_node;
for(let i = 0; i < rows; ++i) {
for(let j = 0; j < cols; ++j) {
let N = nodes[i*rows + j];
let d = (N.pos.x - mouseX)*(N.pos.x - mouseX) + (N.pos.y - mouseY)*(N.pos.y - mouseY);
if(d < min_distance) {
min_distance = d;
closest_node = N;
}
}
}
closest_node.fixed = true;
}