Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
How do I temporarily multiply a vector in p5.js?

I have an object called Boid which has a position and a velocity vector (the direction of movement). When updating the position, I want to apply a factor which the user can control. The following script does not work, however:

let speedFactor = 0.1; //ranges from 0 to 2

class Boid {
    constructor(x, y) {
        this.position = createVector(x, y);
        this.velocity = p5.Vector.random2D();
    }

    update() {
        this.position.add(this.velocity * speedFactor); // doesn't work
    }
}

I also tried to use things like speedFactor = createVector(0.1, 0.1) or = [0.1, 0.1], but it doesn't work.

If I use this.velocity.mult(speedFactor), this will affect the velocity vector, which I don't want (e.g. because if speedFactor == 0, this.velocity will get messed up). I have tried to create a copy of the velocity vector to overcome this by using Object.assign({}, this.velocity) or JSON.parse(JSON.stringify(this.velocity)), but somehow that doesn't work neither.

Most of the time I get the error p5.Vector.prototype.mult: x, y, or z arguments are either undefined or not a finite number.

What would be the best to do here?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Copy the vector, then multiply it with the normal mult method

let speedFactor = 0.1; //ranges from 0 to 2

class Boid {
    constructor(x, y) {
        this.position = createVector(x, y);
        this.velocity = p5.Vector.random2D();
    }

    update() {
        this.position.add(this.velocity.copy().mult(speedFactor));
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!