所以我正在制作一款愤怒的小鸟游戏,我使用的是p5.js和matter.js.

我在游戏中创建了一个MouseConstraint来移动连接到弹弓上的鸟,但我也能够移动输出中的所有身体.

如何将MouseConstraint仅附加到单个身体,即本例中的鸟,以便我只能移动该特定对象,而不能移动其他对象?

如果不能的话,有没有其他方法可以让我用弹弓呢?

推荐答案

您可以使用collision filters:

const makeBox = (x, y, w, h, props, elem) => ({
  w, h, body: Matter.Bodies.rectangle(
    x, y, w, h, props
  ),
  elem,
  render() {
    const {x, y} = this.body.position;
    this.elem.style.top = `${y - this.h / 2}px`;
    this.elem.style.left = `${x - this.w / 2}px`;
    this.elem.style.transform = `rotate(${this.body.angle}rad)`;
  },
});
const boxes = [...document.querySelectorAll(".box")]
  .map((el, i) =>
    makeBox(
    // x             y  w   h
      100 * i + 100, 0, 40, 30,
      {collisionFilter: i === 0 ? {category: 0b10} : {}},
      el,
    )
  );
const ground = Matter.Bodies.rectangle(
  // x    y    w    h
     200, 200, 400, 120, {
    isStatic: true,
  }
);
const engine = Matter.Engine.create();
const mouseConstraint = Matter.MouseConstraint.create(
  engine, {
    collisionFilter: {mask: 0b10},
    element: document.body
  }
);
Matter.Composite.add(
  engine.world, [
    ...boxes.map(e => e.body), ground, mouseConstraint
  ]
);
(function rerender() {
  boxes.forEach(e => e.render());
  Matter.Engine.update(engine);
  requestAnimationFrame(rerender);
})();
.box {
  position: absolute;
  background: #d00;
  transition: background 0.2s;
  width: 40px;
  height: 30px;
  cursor: move;
}
.box:not(:first-child) {
  background: #111;
  cursor: not-allowed;
}
.box:first-child:hover {
  background: #f00;
}

#ground {
  position: absolute;
  background: #666;
  top: 140px;
  height: 120px;
  width: 400px;
}

html, body {
  position: relative;
  height: 100%;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.18.0/matter.min.js"></script>
<div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
<div id="ground"></div>

在这里,鼠标约束被赋予了0b10的掩码,并且被允许与鼠标交互的唯一实体的红色框被设置为0b10的类别.

默认掩码值为32位全部设置,即4294967295/0xffffffff.您可能希望更精确,只禁用第一位:0xfffffffe.这允许鼠标约束与除2以外的其他类别交互,仅禁用与类别1的交互.

要创建相反的情况,即鼠标与除红色框之外的任何实体交互,可以将鼠标约束的遮罩设置为禁用第二个最低有效位的值,如0b10xfffffffd.

另见:

Javascript相关问答推荐

Chromium会将URL与JS一起传递到V8吗?

如何解决useState错误—setSelect Image不是函数''

为什么我的getAsFile()方法返回空?

对路由DOM嵌套路由作出react

用于在路径之间移动图像的查询

为什么我的自定义元素没有被垃圾回收?

当我在Reaction中创建一个输入列表时,我的输入行为异常

TypeError:无法读取未定义的属性(正在读取';宽度';)

面对代码中的错误作为前端与后端的集成

未捕获的运行时错误:调度程序为空

如何找到带有特定文本和测试ID的div?

将Auth0用户对象存储在nextjs类型脚本的Reaction上下文中

如何在下一个js中更改每个标记APEXCHARTS图表的 colored颜色

如何在Reaction中清除输入字段

如何使用Reaction路由导航测试挂钩?

使用静态函数保存 node 前的钩子

如果查询为空,则MongoDB将所有文档与$in匹配

Chart.js根据 Select 显示数据

Vuejs:从声音数组中排除最后播放的声音

用于查找以开头和结尾的单词的正则表达式