p5.Vector returns strange and negative x and y values

please format code with </> button * homework policy * asking questions

I was experimenting with one of Shiffman’s NOC examples. To be specific the steering behavior one. I added a target for my vehicle with the createVector() method (x = 200, y = 300). But when I ran the code, those x and y values turned to negative 0 point something. And it returns slightly different values each frame.
Here’s the console:

Here’s the sketch file:

let mover = new Array(1);
var pos;

function setup() {
				createCanvas(345,400);
				
				pos = createVector(200, 300);
				

				for(var i = 0; i < mover.length; i++) {
								mover[i] = new Mover(random(2), 30,30);
				}
}

function draw() {

				background(51);
				
				for(var i = 0; i < mover.length; i++) {
								
								mover[i].seek(pos);
								
								mover[i].update();
								mover[i].display();
								mover[i].checkEdge();
				}
				
				//console.log(pos.x);
				fill(155);
				ellipse(pos.x,pos.y, 10,10);
}


There’s also something strange I noticed. When I print pos.x/pos.y on the setup function, it prints the exact values (200,300). But when I print it inside draw, that’s when things get messy.
Here’s the Vehicle class:

function Mover(m, x, y) {
				this.loc = createVector(x,y);
				this.velocity = createVector(0,0);
				this.accelerate = createVector(0,0);
				
				this.mass = m;
				
				var maxSpeed = 5;
				var maxForce = 0.1;
			
				this.update = function() {
								this.velocity.add(this.accelerate);
								this.loc.add(this.velocity);
								
								this.accelerate.mult(0);
				}
				
				this.display = function() {
								stroke(0);
								fill(255);
								
								ellipse(this.loc.x, this.loc.y, this.mass*16, this.mass*16);
				}
				
				this.checkEdge = function() {
								if(this.loc.x < 0 || this.loc.x > width) {
												this.velocity.x *= -1;
								}
								if(this.loc.y < 0 || this.loc.y > height) {
												this.velocity.y *= -1;
								}
				}
				
				this.applyForce = function(force) {
								var f = force.div(this.mass);
								this.accelerate.add(f);
				}
				
				this.seek = function(target) {
								var desired = target.sub(this.loc);
								desired.setMag(maxSpeed);
								
								var steer = desired.sub(this.velocity);
								steer.limit(maxForce);
								
							 this.applyForce(steer);
				}
}

I searched a lot around but didn’t find any solution. A brief explanation would be really helpful.

const desired = p5.Vector.sub(target, this.loc);

1 Like

It worked :slightly_smiling_face:. But can you explain why it didn’t work with my code?

target.sub(this.loc); mutates the parameter target, which is the passed argument pos: mover[i].seek(pos);

p5.Vector.sub(target, this.loc); automatically creates a target p5.Vector object (copy() of the 1st parameter v1) which stores the result between the 2 passed p5.Vector object arguments:

1 Like