VickTree
VickTree

Reputation: 909

Understanding matter.js code for Box: this, push and pop

I am new to JavaScript and having a difficult time understanding the following code snippet intuitively. It is code used to make a box in some physics engine (matter.js)

function Box(x, y, w, h){
    this.body = Bodies.rectangle(x,y,80,80);
    this.w = w;
    this.h = h;
    World.add(world, this.body)

    this.show = function(){
        var pos = this.body.position;
        var angle = this.body.angle;

        push();
        translate(pos.x, pos.y);
        rect(0,0,this.w,this.h);

        pop();
    }
}
box1 = new Box(200,100,50,50)
function draw() {
background(51);
box1.show();

}

My questions are this:

Upvotes: 2

Views: 787

Answers (1)

colemars
colemars

Reputation: 1098

why not just use w or h, why assign "this.w" to w and "this.h" to h

this allows the w and h to be properties of the Box. After, if you were to say

box1 = new Box(10,10,10,10)
console.log(box1.w, box1.h)

you would be able to see and manipulate those properties. Because your rectangle is using these properties to draw itself if you manipulate those properties the drawing of your rectangle will change as well.

i am confused by the push(). why is nothing in the parenthesis? what is it adding by default?

I believe you're looking at code utilizing the p5.js library. push() and pop() in p5.js access the draw state. Essentially, push() is 'begin drawing' and pop() is 'stop drawing'. So, here they access the draw state, draw a rectangle, and then close the draw state.

You can read more on p5's documentation.

Upvotes: 2

Related Questions