xxxxxxxxxx
108
const SIZE = 6;
const COLLISION_MARGIN = 12;
var line0 = null;
var point0 = null;
var collX = false;
var collY = false;
function setup() {
createCanvas(400, 400);
line0 = [createVector(50, 300), createVector(370, 300)];
point0 = createVector(200, 300);
}
function draw() {
if (mouseIsPressed) {
let mousePos = createVector(mouseX, mouseY);
if (currPoint) {
currPoint.x = mousePos.x;
currPoint.y = mousePos.y;
} else {
let diff = p5.Vector.sub(point0, mousePos);
if ((diff.x * diff.x) + (diff.y * diff.y) < SIZE * SIZE) {
currPoint = point0;
} else
for (let i = 0; i < 2; i++) {
let diff = p5.Vector.sub(line0[i], mousePos);
if ((diff.x * diff.x) + (diff.y * diff.y) < SIZE * SIZE) {
currPoint = line0[i];
break;
}
}
}
} else {
currPoint = null;
}
slope = (line0[1].y - line0[0].y) /
(line0[1].x - line0[0].x);
xCol = null;
yCol = null;
if (point0.x >= min(line0[0].x, line0[1].x) &&
point0.x < max(line0[0].x, line0[1].x)) {
xCol = createVector(point0.x,
slope * (point0.x - line0[0].x) +
line0[0].y);
if (abs(xCol.y - point0.y) < COLLISION_MARGIN)
collX = true;
else
collX = false;
} else {
collX = false;
}
if (point0.y >= min(line0[0].y, line0[1].y) &&
point0.y < max(line0[0].y, line0[1].y)) {
yCol = createVector((point0.y - line0[0].y) / slope +
line0[0].x,
point0.y);
if (abs(yCol.x - point0.x) < COLLISION_MARGIN)
collY = true;
else
collY = false;
} else {
collY = false;
}
background(220);
strokeWeight(2);
stroke(0);
line(line0[0].x, line0[0].y, line0[1].x, line0[1].y);
let normal = createVector(-(line0[1].y - line0[0].y),
(line0[1].x - line0[0].x));
line(point0.x,
point0.y,
point0.x + normal.x,
point0.y + normal.y);
stroke(200, 0, 0);
if (xCol)
line(point0.x, point0.y, xCol.x, xCol.y);
if (yCol)
line(point0.x, point0.y, yCol.x, yCol.y);
strokeWeight(1);
stroke(0);
fill(255, 255, 0);
circle(line0[0].x, line0[0].y, SIZE);
circle(line0[1].x, line0[1].y, SIZE);
circle(point0.x, point0.y, SIZE);
noStroke();
fill(0);
text('Colliding: ' + collX + collY, 10, 16);
text(xCol + ' | ' + yCol, 10, 32);
text('Slope: ' + slope, 10, 48);
}