xxxxxxxxxx
121
// Position of 2 people
let x1, y1, x2, y2;
// Position of division
let midX, midY;
let mode = 2;
// Average midpoints
let mids = [];
// Average angles
let dxys = [];
function setup() {
createCanvas(windowWidth, windowHeight);
// Start off on a diagonal
x1 = width * 0.25;
y1 = height * 0.25;
x2 = width * 0.75;
y2 = height * 0.75;
}
function draw() {
background(0);
// Calculate the mid-point between 2 points
midX = (x1 + x2) / 2;
midY = (y1 + y2) / 2;
mids.push({
x: midX,
y: midY
});
stroke(255);
noFill();
// Draw the vertical division
if (mode == 0) rect(midX, -1, width - midX, height + 1);
// Draw the horizontal division
else if (mode == 1) rect(0, midY, width, height - midY);
else {
// Calculate the relative xy position between the 2 points
let dxy = {
x: x2 - x1,
y: y2 - y1
};
// Store it for averaging over time
dxys.push(dxy);
// Only store 120 frames
if (dxys.length > 120) dxys.shift();
if (mids.length > 120) mids.shift();
let avgMid = {
x: 0,
y: 0
};
for (let mid of mids) {
avgMid.x += mid.x;
avgMid.y += mid.y;
}
avgMid.x /= mids.length;
avgMid.y /= mids.length;
// Set-up an object to store the average relative xy position over time
let avgDXY = {
x: 0,
y: 0
};
// Calculate the average relative xy position
for (let aXY of dxys) {
avgDXY.x += aXY.x;
avgDXY.y += aXY.y;
}
avgDXY.x /= dxys.length;
avgDXY.y /= dxys.length;
// Calculate the average angle
let angle = atan(avgDXY.y / avgDXY.x);
if(angle < 0) angle += PI;
if(avgDXY.y < 0) angle += PI;
console.log(angle);
// Rotate the canvas to that angle
// to draw the dividing rectangle
push();
translate(avgMid.x, avgMid.y);
rotate(angle);
// Draw the xy division
line(0, -width, 0, width);
pop();
}
fill('red');
// Draw the people
ellipse(x1, y1, 10, 10);
ellipse(x2, y2, 10, 10);
// Draw the midpoint
ellipse(midX, midY, 20, 20);
}
// Move the closest point with the mouse
// mouse is being dragged
function mouseDragged() {
let d1 = dist(mouseX, mouseY, x1, y1);
let d2 = dist(mouseX, mouseY, x2, y2);
if (d1 < d2) {
x1 = mouseX;
y1 = mouseY;
} else {
x2 = mouseX;
y2 = mouseY;
}
}
function keyPressed() {
mode++;
mode %= 3;
}