createVector error : Cannot set properties of undefined

a really simple script trying to use createvector to make a sliding box.

let b;
function setup() {
createCanvas(800, 800);
b=new box();
b.startp(200,500,400,700)
b.slided(20,100,40,80)
}

function draw() {
background(220);
b.slidem(0.1);
b.drawb();
b.resetr(500);

}

class box{
construator(){
this.org1=createVector(0,0);
this.org2=createVector(0,0);
this.dir1=createVector(0,0);
this.dir2=createVector(0,0);
this.pos1=createVector(0,0);
this.pos2=createVector(0,0);

}
startp(x,y,xx,yy){
this.org1.x= x;
this.org1.y= y;
this.org2.x= xx;
this.org2.y= yy;
}
slided(x,y,xx,yy){
this.dir1.x=x;
this.dir1.y=y;
this.dir2.x=xx;
this.dir2.y=yy;

}
slidem(x){
this.pos1.x += xthis.dir1.x;
this.pos1.y += x
this.dir1.y;
this.pos2.x += xthis.dir2.x;
this.pos2.y += x
this.dir2.y;
}
drawb(){
beginShape()
vertex(this.org1.x+this.pos1.x,this.org1.y+this.pos1.y);
vertex(this.org1.x+this.pos1.x+this.dir1.x,this.org1.y+this.pos1.y+this.dir1.y);
vertex(this.org2.x+this.pos2.x+this.dir2.x,this.org2.y+this.pos2.y+this.dir2.y);
vertex(this.org2.x+this.pos2.x,this.org2.y+this.pos2.y);

}
resetr(x){
if(pow(this.pos1.x,2)+pow(this.pos1.y,2)>pow(x,2)){
this.pos1.x=0;
this.pos1.y=0;
this.pos2.x=0;
this.pos2.y=0;
}
}
}

p5js always says

TypeError: Cannot read properties of undefined (reading ‘x’) at box.slidem (/sketch.js:43:10) at draw (/sketch.js:11:5) at p5._main.default.redraw

​in every line that trying to read the x or y value out of any vector, like
this.org1.x= x;
this.dir1.x=x;
this.pos1.x += x*this.dir1.x;
vertex(this.org1.x+this.pos1.x,this.org1.y+this.pos1.y);

and i do not understand why. I spent 3 hours try to make simpler versions of this, and they all worked, so I supposed the way I use these function is correct. I just dont see any mistake I could make here. It almost seems like a bug.

Looks like there are a few typos:

class box{
construator()

should be constructor(). After that, you’ll get another error where you’ll need to change xthis.dir1.x to this.dir1.x and the same for the other xthis in that method. Finally, you’ll need to add endShape() at the end of drawb in order to close the shape (or you won’t see anything)

1 Like

that works, thank you so much. i am surprised that p5js did not recognize default function typos like processing does.

1 Like