xxxxxxxxxx
49
// Demo code for my blog at https://arnauld-alex.com/
let vectorA;
let vectorB;
let vectorC;
let vectorD;
const xShift = 130;
const yShift = 70;
function setup() {
createCanvas(400, 200);
vectorA = createVector(200, 100);
vectorB = createVector(100, 50); // Same exact direction (scaled)
vectorC = createVector(-100, -50); // Opposite exact direction (scaled)
vectorD = createVector(-50, 100); // Perpendicular
let normalizedA = vectorA.copy().normalize();
let normalizedB = vectorB.copy().normalize();
let normalizedC = vectorC.copy().normalize();
let normalizedD = vectorD.copy().normalize();
console.log(`Dot product of A and B: ${normalizedA.dot(normalizedB)}`);
console.log(`Dot product of A and C: ${normalizedA.dot(normalizedC)}`);
console.log(`Dot product of A and D: ${normalizedA.dot(normalizedD)}`);
}
function draw() {
background(2, 6, 23);
// Draw vectors
drawVector(vectorA, 'A', color(255));
drawVector(vectorB, 'B', color(255, 0, 0));
drawVector(vectorC, 'C', color(0, 255, 0));
drawVector(vectorD, 'D', color(70, 150, 255));
}
function drawVector(vector, label, col) {
stroke(col);
strokeWeight(4);
line(xShift, yShift, xShift + vector.x, yShift + vector.y);
strokeWeight(1);
fill(col);
text(label, xShift + vector.x + 10, yShift + vector.y - 5);
strokeWeight(8);
point(xShift + vector.x, yShift + vector.y);
}