Limit The Length Of A Line
I'm trying to draw a line that represents a 'slingshot' and I want it to have a maximum draw length. in p5 I'm drawing a line between positionA and positionB: line(posA.x, posA.y,
Solution 1:
The Euclidean distance between 2 points is calculated by sqrt(dx*dx + dy*dy)
.
If you divide the vector of one point to the other by its length then you get the Unit vector with length 1.
Calculate the unit vector from posA
to posB
and multiply it by 40:
// (dx, dy): vector form "posA" to "posB" let dx = posB.x-posA.x;
let dy = posB.y-posA.y;
// dist : euclidean distance, length of the vecotr let dist = Math.sqrt(dx*dx + dy*dy);
// (ux, uy): unit vector form 'posA' in direction to 'posB', with length 1 let ux = dx / dist;
let uy = dy / dist;
// (x2, y2): point with a distance of 40 from "posA" an the vector to "posB"let x2 = posA.x + ux * 40;
let y2 = posA.y + uy * 40;
line(posA.x, posA.y, x2, y2);
In p5.js you can use p5.Vector
for all this calculations.
.sub()
subtracts two points and calculates the vector.normalize()
computes the unit vector with length 1.mult()
scales the vector.add()
adds the vectors to the point
let A = createVector(posA.x, posA.y);
let B = createVector(posB.x, posB.y);
let P = B.sub(A).normalize().mult(40).add(A);
line(posA.x, posA.y, P.x, P.y);
See the example:
functionsetup() {
createCanvas(200, 200);
}
functiondraw() {
background(0, 0, 0);
stroke(255, 0, 0);
strokeWeight(5);
let A = createVector(width/2, height/2);
let B = createVector(mouseX, mouseY);
let P = B.sub(A).normalize().mult(40).add(A);
line(A.x, A.y, P.x, P.y);
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>
Post a Comment for "Limit The Length Of A Line"