Matter.js 在物体上的鼠标点击

10

我有一些关于matter.js库的代码,类似于以下内容:

// create two boxes and a ground
var boxA = Bodies.rectangle(400, 200, 80, 80);
var boxB = Bodies.rectangle(450, 50, 80, 80);
var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });

// add all of the bodies to the world
World.add(engine.world, [boxA, boxB, ground]);
Events.on(engine, 'tick', function(event) {
  if (mouseConstraint.mouse.button == 0){
    alert("what is clicked?");
  }
});

在事件处理程序中,有没有办法告诉我哪个

boxA
boxB
被鼠标点击了?


1
看看在Matter.MouseConstraint.update中是如何完成的。 - liabru
@liabru,在 OP 的情况下应该如何实现? - Jesse Hattabaugh
2个回答

2

为了详细说明这个答案,下面是一个可运行的例子,展示如何在事件处理程序中使用mouseConstraint.body来确定被点击的物体:

const engine = Matter.Engine.create();
const render = Matter.Render.create({
  element: document.body,
  engine: engine,
});
const bodies = [
  Matter.Bodies.rectangle(
    400, 310, 810, 60, {isStatic: true, angle: 0.0}
  ),
  ...[...Array(100)].map(() =>
    Matter.Bodies.rectangle(
      Math.random() * 400,     // x
      Math.random() * 100,     // y
      Math.random() * 50 + 10, // w
      Math.random() * 50 + 10, // h
      {angle: Math.random() * (Math.PI * 2)},
    )
  ),
];
const mouseConstraint = Matter.MouseConstraint.create(
  engine, {element: document.body}
);
const runner = Matter.Runner.create();
Matter.Events.on(runner, "tick", event => {
  if (mouseConstraint.body) {
    Matter.Composite.remove(engine.world, mouseConstraint.body);
  }
});
// also possible, testing the condition on mousedown only:
//Matter.Events.on(mouseConstraint, "mousedown", () => {
//  if (mouseConstraint.body) {
//    Matter.Composite.remove(engine.world, mouseConstraint.body);
//  }
//});
Matter.Composite.add(engine.world, [...bodies, mouseConstraint]);
Matter.Runner.start(runner, engine);
Matter.Render.run(render);
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.js"></script>

您还可以使用Matter.Query.point,并在单击时传递鼠标的X和Y位置,以获取该点上的一组物体。请保留HTML标签。


请注意,这不适用于mouseup事件。在mouseup上测试mouseConstraint.body属性总是显示它未设置。这让我困惑了一段时间,但这很有道理,因为当鼠标按钮松开时,当前没有任何body被触摸,因为鼠标单击刚刚结束。我的解决方案是在mousedown上进行测试,如上所示。 - Mike

0

mouseConstraint.body 包含被点击的物体。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接