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?

1 Answer

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)); } } 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like