cannon.js icon indicating copy to clipboard operation
cannon.js copied to clipboard

How to predict collisions?

Open Nikola-Obreshkov opened this issue 7 years ago • 3 comments

The code bellow is taken from the collisions demo:

      var demo = new CANNON.Demo();
      demo.addScene("Sphere / sphere",function(){
          var world = setupWorld(demo);
          // Sphere 1
          var sphereShape = new CANNON.Sphere(1);
          var b1 = new CANNON.Body({ mass: 5 });
          b1.addShape(sphereShape);
          b1.position.set(5,0,0);
          b1.velocity.set(-5,0,0);
          b1.linearDamping = 0;
          world.addBody(b1);
          demo.addVisual(b1);

          // Sphere 2
          var b2 = new CANNON.Body({ mass: 5 });
          b2.addShape(sphereShape);
          b2.linearDamping = 0;
          b2.position.set(-5,0,0);
          b2.velocity.set(5,0,0);
          world.addBody(b2);
          demo.addVisual(b2);
        });

In this case how can I predict the collision point and velocity vectors of both object after the collision without rendering the scene? I want to implement a guide line showing what will happen before the actual rendering of the scene.

Nikola-Obreshkov avatar Nov 04 '17 07:11 Nikola-Obreshkov

The CANNON.Demo may not be built for this purpose. But you could step through and record the simulation outcome without rendering.

If you recorded the positions and rotations of objects at each frame, you could later loop through each frame and apply this to objects in a THREE.js scene to get the exact same result each playback.

There are collision events you can listen for on the body and world classes:

world.addEventListener('beginContact', ...);
world.addEventListener('endContact', ...);`

and

body.addEventListener('collide', ...);

TerryHibbert avatar Nov 13 '17 05:11 TerryHibbert

This is an interesting approach. But after some research I notice that there are a family of raycast functions of the world object such as: var isHit = world.raycastClosest(from, to, options, result); which emits a ray object and populates a raycast result object. Then:

if ( result.hasHit ) {
      var hitShape = result.shape;
      var hitBody = result.body;
}

will predict potential collisions at given moment. To sum up:

  • in a static world raycasting is a preferable build-in mechanism for collision detection
  • in a dynamic world taking into account the objects mass, velocities, trajectories, friction, etc. simulating the world behind the curtains, i.e. without rendering anything, may be the only way to forecast collisions

Nikola-Obreshkov avatar Nov 13 '17 16:11 Nikola-Obreshkov

world.addEventListener('beginContact', ...) world.addEventListener('endContact', ...);`

这两个方法无效了。监听不到事件

DavidHome avatar Jun 02 '18 07:06 DavidHome