【问题标题】:I want to create matter.js bodies at the press of a button and I'm running into errors我想按一个按钮来创建 matter.js 主体,但我遇到了错误
【发布时间】:2021-06-15 16:34:45
【问题描述】:

我想创建一个基本的物理沙盒应用程序,使用 matter.js 作为物理引擎并使用 p5.js 进行渲染。我的想法是在按下特定按钮时生成身体(左键用于有弹性的身体,右键用于沉重的身体等)。我使用此代码进行按键控制:

if (keyIsDown(LEFT_ARROW)) {
    rubber2 = new Rubber(100,40,15) 
    rubber2.display()
}

rubber2.display();

这是Rubber 类:

class Rubber {
  constructor(x, y, r) {
    var options = {
      'restitution': 1.5,
      'density': 0.9,
      'friction': 1
    }
    this.x = x;
    this.y = y;
    this.r = r
    this.body = Bodies.circle(this.x, this.y, (this.r - 20) / 2, options)
    World.add(world, this.body);
  }
  
  display() {
    var rubberpos = this.body.position;
    push()
    translate(rubberpos.x, rubberpos.y);
    rectMode(CENTER)
    strokeWeight(4);
    stroke("green");
    fill("yellow");
    ellipse(0, 0, this.r)
    pop()
  }
}

这给了我诸如rubber2 is not definedrubber2 之类的错误,仅在按住键且没有任何物理特性时才显示。根本不显示球确实会创建身体但不可见。

【问题讨论】:

    标签: javascript p5.js matter.js


    【解决方案1】:

    您显示的代码似乎很合理,因此仍然不足以真正重现您可能遇到的问题。经过清理并将其变成可运行的示例后,我可以提供:

    class Rubber {
      constructor(x, y, r, engine) {
        const options = {
          restitution: 1.5,
          density: 0.9,
          friction: 1,
        };
        this.body = Matter.Bodies.circle(x, y, r, options);
        Matter.Composite.add(engine.world, this.body);
      }
      
      display() {
        const {position: {x, y}, circleRadius: r} = this.body;
        push();
        translate(x, y);
        strokeWeight(4);
        stroke("green");
        fill("yellow");
        ellipse(0, 0, r);
        pop();
      }
    }
    
    let rubbers = [];
    let engine;
    
    function setup() {
      createCanvas(500, 200);
      engine = Matter.Engine.create();
      //engine.gravity.y = 0;
    }
    
    function draw() {
      if (keyIsDown(LEFT_ARROW)) {
        rubbers.push(new Rubber(mouseX, mouseY, 15, engine));
      }
    
      background(30);
      
      rubbers = rubbers.reduce((nextGen, e) => {
        const {position: {x, y}, circleRadius} = e.body;
        
        if (y + circleRadius <= height) {
          nextGen.push(e);
          e.display();
        }
        
        return nextGen;
      }, []);
      
      Matter.Engine.update(engine);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.18.0/matter.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>
    <p>Press the left arrow key to create a ball where the mouse is</p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 2022-08-20
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      相关资源
      最近更新 更多