Hello i’m creating an box where you can drag and drop some objects but currently the objects can be dragged beyond the box i.e in the z axis. I want the object to be only dragged in the x-y axis no matter how the camera rotates…
see the image for more details.
one more thing to consider, if i rotate the camera, then the object can be dragged anywhere… i want to forbid that action too… i want the object to move only with in the box height width.
Since you are using no real collision detection or collider system, you have to manually define a valid range in which a translation of the object is allowed. You can then check per frame if the position of the object is still in this range. If the object exceeds the limits, you just clamp the position. This approach is fast and easy to implement but not very flexible.
I assume you are using THREE.DragControls, right? Have you considered to use a control system similar to the editor? It combines EditorControls and TransformControls. The resulting interaction might be more appropriate for your app than THREE.DragControls.
thank you @Mugen87 for your reply… i’ve implemented the transformControls but the drag point is fixed to a single point. can i change it to any custom size? like i want to drag the object by clicking anywhere on the object?
I had the same requirement, but only allow to move on X axis. I did it the following way. And
const objects = [];
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );
objects.push( cube );
const dragControls = new THREE.DragControls(objects, camera, renderer.domElement);
dragControls.addEventListener( 'dragstart', function ( event ) {
console.log('drag start');
});
dragControls.addEventListener ( 'drag', function( event ){
console.log('drag');
event.object.position.z = 0; // This will prevent moving z axis, but will be on 0 line. change this to your object position of z axis.
})
dragControls.addEventListener( 'dragend', function ( event ) {
console.log('drag end');
});
If you you are working with OrbitControl check out the following link. @Mugen87 has answered a nice solution.