1

I was wondering if anyone knows how to implement hover effect with Matter.js. I have checked their documentation but could not figure out. Though, there is Mouse - mousedown, mouseup, mousemove and more.

I have researched but I could not find any useful information. I know the shapes/physics are rendered inside the canvas. Any information or advice would be very helpful.

4

2 回答 2

2

If you want to find the Body which is below the mouse/given point, you can use

Matter.Query.point

docs.

If you want to make Body hover:

I have once created a hover effect using Box2d, but I guess in might be done the same way in matter.js. Just have a look at the illustration below.

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

To make a body hover, you need to apply a force to it, which opposite to gravity. Therefore you need to figure out how strong this force needs to be, which should be zero if the body is above the height to hover and should get stronger the closer the body is at the ground.

To get this information you can use ray casting and send one or more rays from the body towards the ground (opposite to gravity). In case the ray(s) intersect with the floor/ground to hover on, you can calculate the length from the body to the intersection. If the length is larger than the height to hover, the force can be set to zero, if it is equal or below, you can scale the force in some inverted proportion to the length, such that it is strong when the body is low. The exact method/function depends on the effect you try to achieve.

When I did it, I calculated around 10 rays and used the average of them, this way the body was able to »climb«

You may have a look here where I was seeking for help when I did this.

Here is a great tutorial about it, unfortunately in Box2d, but the physics them self shouldn't be different.

于 2019-03-20T12:10:02.973 回答
2

I have figured out the way to implement hover behavior. To do that I used Matter.Query.point and "mousemove"(Matter.Events.on) method. Thanks for @philipp above for pointing me out the right direction. Here is the simple code.

//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

});

Happy coding! :)

于 2019-04-04T07:45:28.877 回答