I have a strange problem with p5.js
. Basically, there is one source of gravity force (red square) and one blue square (called pixel in code) that orbits around a red square. proc()
function makes one step in time and proceeds physics of both objects and draw()
function just draws those two squares. The question is about my sketch.js file. When it's in order:
env.draw();
env.proc();
it works well but when it's:
env.proc();
env.draw();
it works very strangely. Here are quick previews:
Working well: http://home.elka.pw.edu.pl/~eprokopc/goodGrav/index.html
Working badly: http://home.elka.pw.edu.pl/~eprokopc/badGrav/index.html
Github repo: https://github.com/kekore/BadGravity
Both examples differ only those two lines order in sketch.js
. I'm just curious why squares are drawn like that.
The "weird" behavior where sizes change depending on where draw and proc are called is caused by the call to scaleTo from the Vector class. Vector scaleTo calls scale which calls the p5 scale function even though Vector has its own scale function.
class Vector{
constructor(initX,initY){
this.x = initX;
this.y = initY;
}
scale(a){
this.x = this.x * a;
this.y = this.y * a;
}
scaleNC(a){
return new Vector(this.x*a,this.y*a);
}
scaleTo(len){
scale(len/this.length());
}
}
If the desired behavior is for scaleTo to call Vector.scale modify scaleTo:
scaleTo(len){
this.scale(len/this.length());
}