有没有办法用 p5 绘制 matter.js 复合图?

Is there a way to draw a matter.js composite with p5?

我最近在 2017 年的编码火车频道上看到了 matter.js,我已经设法复制了这些视频中显示的示例,但现在我想做一些更高级的事情。 documentation used to create a soft body in the matter.js demos 中有一个名为 stack 的复合模块,但我想知道是否有办法使用 p5 来绘制它。

This 是我到目前为止得到的,任何帮助表示赞赏

我认为您的代码的主要问题是您没有将 Composite 添加到 world。这是一个有一些其他调整的工作示例:

const {
  Bodies,
  Common,
  Composites,
  Constraint,
  Engine,
  Runner,
  World
} = Matter;

var engine;
var world;
var particles = [];
var boundaries = [];
var composi1;
var composi2;

function setup() {
  createCanvas(400, 400);

  engine = Engine.create();
  world = engine.world;

  // Use a runner to actually run the simulation
  const runner = Runner.create();
  Runner.run(runner, engine);

  // Add two composites so we can see them interact
  composi1 = new softbodi(100, 50, 4, 4, 0, 0, true, 20);
  composi2 = new softbodi(50, 300, 4, 2, 0, 0, true, 20);

  boundaries.push(new Boundary(200, height, width, 50, 0));
}

function draw() {
  background(51);

  for (var i = 0; i < boundaries.length; i++) {
    boundaries[i].show();
  }

  composi1.show();
  composi2.show();
}

function softbodi(
  xx,
  yy,
  columns,
  rows,
  columnGap,
  rowGap,
  crossBrace,
  particleRadius) {

  this.r = particleRadius;

  this.composite = Composites.stack(
    xx,
    yy,
    columns,
    rows,
    columnGap,
    rowGap,
    function(x, y) {
      return Bodies.circle(x, y, particleRadius);
    }
  );

  this.mesh = Composites.mesh(this.composite, columns, rows, crossBrace);

  // Dont forget to add you composite to the world
  World.add(world, this.composite);

  this.show = function() {
    var parr = [];
    parr = Matter.Composite.allBodies(this.composite);
    for (var i = 0; i < parr.length; i++) {
      var pos = parr[i].position;
      var angle = parr[i].angle;
      push();
      translate(pos.x, pos.y);
      rotate(angle);
      rectMode(CENTER);
      strokeWeight(1);
      stroke(255);
      fill(127);
      ellipse(0, 0, this.r * 2);
      pop();
    }
  };
}

function Boundary(x, y, w, h, a) {
  var options = {
    friction: 0,
    restitution: 0.95,
    angle: a,
    isStatic: true
  };
  this.body = Bodies.rectangle(x, y, w, h, options);
  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);
    rotate(angle);
    rectMode(CENTER);
    strokeWeight(1);
    noStroke();
    fill(0);
    rect(0, 0, this.w, this.h);
    pop();
  };
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.17.1/matter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>