# PVectors - Help new beginner follow

need help, how can a rectangle (or something) follow a next rectangle that is at different position?

Depends what method you want to use. This would normally involve tracking the location of the first shape, assigning a position a velocity and an acceleration to the second shape. The acceleration is what allows the second shape to move according to the position of the first shape.

Depending on which method you are using it will involve trig or the use of PVectors.

For help on PVectors I recommend Khan aacdemy.

or

if using standard trig
shape 2 will have

xpos
ypos

xvel
yvel

xacc
yacc

acceleration is usually just a constant ie 0.2, depending on how fast you want the shape to accelerate,

you add the acceleration to the velocity( remember to limit your max velocity otherwise you’ll end up with infinite speed) this is easier to do in PVector.

here is p5 code for a mouse tracker.

`````` this.update = function () {
var mouse = new PVector(mouseX, mouseY);
var mx = mouseX;
var my = mouseY;
var dy = (my - this.y)*0.0005;
var a = 1.00;
var dx = (mx - this.x )*0.0005;
var dir = atan2(dy,dx);
this.dir = (map(dir,-180,180,0,360)-1)*a;

if(my>this.y){
dy = -dy;
}
if(mx>this.x){
dx =  -dx;
}
this.ax = dx;
this.ay = dy;

if(this.vx>=4){
this.vx = 4;
}
if(this.vx<=-4){
this.vx = -4;
}
if(this.vy>=4){
this.vy = 4;
}
if(this.vy<=-4){
this.vy = -4;
}
this.vx += this.ax;
this.vy += this.ay;

this.x += this.vx*cos(this.dir);
this.y += this.vy*sin(this.dir);
};
``````

note here that the acceleration is the 0.00005.

Ive never replicated this using PVectors so I cant help you a great deal there, however the code is much more elegant if you decide to use that option.

2 Likes

full code

https://editor.p5js.org/paulgoux/sketches/lDlcUhKp8
check the update function for the code.

please note this is very crude.

2 Likes