How to implement collision detection along with Transform Control or Drag Control?

Let’s say I’ve got a scene with multiple boxes defined as follows:

// Box geometry with edges 1
var geometry = new THREE.BoxGeometry(0.80, 1.20, 1.20); //x,y,z
var boxMaterial = new THREE.MeshBasicMaterial({ color: 0xF7DC6F });
var wireFrameMaterial = new THREE.MeshBasicMaterial({ color: 0xD4AC0D, wireframe: true, wireframeLinewidth: 2, transparent: false });
var material = [boxMaterial, wireFrameMaterial];
var cube = THREE.SceneUtils.createMultiMaterialObject(geometry, material);
 
cube.position.set(-0.775, 0.6, -5.415); //x,y,z
scene.add(cube);

What is the proper way to implement collision detection in this scenario which allows me to pick a single cube and drag it with mouse, but only within limits set by other cubes (collision with any cube prevent further move in that direction)? I’ve read about position.clamp, raycasting and so on, but still has no idea how to put it all together. Thanks for any advice.

Two ways. Use a physics engine, or write a very simple one :slight_smile:
Check out the Box3 object, and in particular .intersectsBox().
This will give you a boolean value of whether a box overlaps another one.

Ok, lets consider the first option. Ive tried to add canoon.js to my three.js project (using this example https://github.com/schteppe/cannon.js/blob/569730f94a1d9da47967a24fad0323ef7d5b4119/examples/threejs.html), but I wan unable to make canoon,js work together with Transform Control. How to sync positions between those two and make the work together?

Here is an example of using Cannonjs with the DragControls which demonstrates the first part of your question about dragging an object with physics. You can bump the other spheres away with thy object you are dragging.

This is achieved In the animation loop by either updating the Threejs mesh using the Cannonjs body position and quaternion, or updating the Cannonjs body with the Threejs mesh position and quaternion if it is being dragged. I am also setting the velocity and angularVelocity to 0 for the object being dragged.

See highlighted code in the animation loop : https://codesandbox.io/s/cannonjs-with-dragcontrols-9691o?file=/src/client/client.ts:4499-5362

1 Like