如何使用 Matter-js 鼠标仅允许单个物体移动

问题描述 投票:0回答:2

所以我正在制作一款愤怒的小鸟游戏,并且使用 p5.js 和 Matter.js。

我在游戏中创建了一个 mouseConstraint 来移动连接到弹弓的小鸟,但我也可以移动输出中的所有物体。

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

如果这是不可能的,是否有其他方法可以用来使用弹弓?

javascript matter.js
2个回答
0
投票

您可以使用碰撞过滤器

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.20.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 的交互。

要创建相反的情况,即鼠标与除红框之外的任何主体交互,您可以将鼠标约束的掩码设置为关闭第二个最低有效位的内容,例如

0b1
0xfffffffd

另请参阅:


0
投票

要将 mouseConstraint 附加到单个主体,您需要将主体作为第二个参数传递:

mouseConstraint = MouseConstraint.create(engine, {body: bird});
© www.soinside.com 2019 - 2024. All rights reserved.