javascript - 了解 Box : this, 推送和弹出的 Matter.js 代码

标签 javascript this matter.js

我是 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();

}

我的问题是这样的:

  • 为什么不只使用 w 或 h,为什么将“this.w”分配给 w,将“this.h”分配给 h
  • 我对push()感到困惑。为什么括号里什么都没有?它默认添加什么?
  • 与 pop() 相同。它在去除什么?

最佳答案

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 库的代码。 p5.j​​s 中的 push()pop() 访问绘制状态。本质上,push() 是“开始绘图”,pop() 是“停止绘图”。所以,在这里他们访问绘制状态,绘制一个矩形,然后关闭绘制状态。

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

关于javascript - 了解 Box : this, 推送和弹出的 Matter.js 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54636764/

相关文章:

javascript - react 更新问题

coffeescript - 粗箭头 'this' 范围

C++ map 容器

javascript - 为什么我的圆圈以一定 Angular 从直线表面弹起?

javascript - JQuery 日期选择器 : show on input group addon button click

javascript - 如何解决文本字符串必须在嵌套 map 中的 <Text> 内呈现?

javascript - jquery "this"范围作为选择器

matter.js - 在 Matter.js 中触发鼠标/触摸事件

typescript - 在 typescript 项目中导入 matter-js

javascript - 如何通过 ng-click 在 angularjs 中使用键、值对显示表中更多或更少的行