了解 Box 的 matter.js 代码:this、push 和 pop

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

我是 JavaScript 的新手,很难直观地理解以下代码片段。它是用于在某些物理引擎中制作盒子的代码(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();

}

我的问题是:

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

这允许 w 和 h 成为 Box 的属性。之后,如果你说

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

您将能够查看和操作这些属性。因为您的矩形正在使用这些属性来绘制自身,所以如果您操纵这些属性,您的矩形的绘制也会发生变化。

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

我相信您正在查看使用 p5.js 库的代码。 push() 和 p5.js 中的 pop() 访问绘图状态。本质上,push() 是 'begin drawing' 而 pop() 是 'stop drawing'。所以,他们在这里访问绘制状态,绘制一个矩形,然后关闭绘制状态。

您可以在 p5 上阅读更多内容 documentation