如何在Matter.js中实现鼠标悬停行为?

How to implement mouse hovering behavior in Matter.js?

我想知道有没有人知道如何用Matter.js. I have checked their documentation but could not figure out. Though, there is Mouse - mousedown, mouseup, mousemove and more实现悬停效果。

我已经研究过,但找不到任何有用的信息。我知道 shapes/physics 在 canvas 内呈现。任何信息或建议都会非常有帮助。

如果你想找到mouse/given点下方的Body,你可以使用

Matter.Query.point

docs.

如果你想Body悬停:

我曾经使用 Box2d 创建了悬停效果,但我想在 matter.js 中可能会以相同的方式完成。看看下面的插图。

    ^
    |      <-- Force opposite to gravity
+---|---+
|   +   |  <-- Box/player/body
+-+-+-+-+
| | | | |  <-- Rays
  | | |
----+----- <-- Ground to hover on
    |

要使body悬停,您需要对其施加一个与重力相反的力。因此你需要弄清楚这个力需要多大,如果 body 高于悬停高度,它应该为零,并且 body 离地面越近,它应该越强。

要获取此信息,您可以使用光线投射并从 body 向地面(与重力相反)发送一条或多条光线​​。如果光线与 floor/ground 相交以悬停,您可以计算从 body 到交点的长度。如果长度大于悬停的高度,力可以设置为零,如果等于或小于,可以将力与长度成某种反比例缩放,这样当body 低。确切的 method/function 取决于您尝试达到的效果。

当我这样做的时候,我计算了大约 10 条射线并使用它们的平均值,这样 body 就能够 »climb«

你可以看看here我做这个的时候是在哪里寻求帮助的。

Here 是一个很棒的教程,不幸的是在 Box2d 中,但是它们本身的物理应该没有什么不同。

我找到实现悬停行为的方法了。为此,我使用了 Matter.Query.point 和 "mousemove"(Matter.Events.on) 方法。感谢上面的 @philipp 为我指明了正确的方向。这是简单的代码。

//Need to add MouseConstraint for mouse events
 var mConstraint;
 mConstraint = MouseConstraint.create(engine, options);
 Matter.World.add(world, mConstraint);

//Add event with 'mousemove'
Matter.Events.on(mConstraint, 'mousemove', function (event) {
   //For Matter.Query.point pass "array of bodies" and "mouse position"
   var foundPhysics = Matter.Query.point(bodies, event.mouse.position);

  //Your custom code here
  console.log(foundPhysics[0]); //returns a shape corrisponding to the mouse position

});

编码愉快! :)