Ashbury
Ashbury

Reputation: 2346

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, posB.x, posB.y);

posA is the mouse x and y. posB is the position of a circle on the canvas.

What I want to do is limit the length of the line, so that it is never more than 40px long, but still points toward the mouse from the circle.

Upvotes: 2

Views: 1104

Answers (1)

Rabbid76
Rabbid76

Reputation: 210878

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:

function setup() {
    createCanvas(200, 200);
}

function draw() {

    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);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>

Upvotes: 6

Related Questions