xxxxxxxxxx
// Demonstrate the value of the dot product between two vectors
void setup() {
size(640, 360);
}
void draw() {
background(255);
PVector mouseLoc = new PVector(mouseX, mouseY);
PVector centerLoc = new PVector(width/2, height/2);
PVector vectorA = PVector.sub(mouseLoc, centerLoc);
vectorA.normalize();
vectorA.mult(120);
fill(200, 0, 0);
noStroke();
rect(centerLoc.x, centerLoc.y + 10, vectorA.x, 5);
PVector vectorB = new PVector(120, 0);
drawVector(vectorA, centerLoc, 1.0);
drawVector(vectorB, centerLoc, 1.0);
PVector aNorm = vectorA.get();
PVector bNorm = vectorB.get();
aNorm.normalize();
bNorm.normalize();
float dot = aNorm.dot(bNorm);
fill(0);
textSize(30);
text("A · B = " + nf(dot, 1, 3), 10, height - 10);
textSize(20);
text("Dot product of normalized vectors (length = 1.0)", 10, 27);
}
// Renders a vector object 'v' as an arrow and a position 'loc'
void drawVector(PVector v, PVector pos, float scayl) {
pushMatrix();
float arrowsize = 20;
// Translate to position to render vector
translate(pos.x, pos.y);
stroke(0);
strokeWeight(2);
// Call vector heading function to get direction (pointing up is a heading of 0)
rotate(v.heading2D());
// Calculate length of vector & scale it to be bigger or smaller if necessary
float len = v.mag()*scayl;
// Draw three lines to make an arrow
line(0, 0, len, 0);
line(len, 0, len-arrowsize, +arrowsize/2);
line(len, 0, len-arrowsize, -arrowsize/2);
popMatrix();
}