Drag an object only in the x y axis

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.

image

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.

see the image
image

Any help would be appreciated.

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.

2 Likes

I only want to translate on x and z not y it’s woking with this code but the drag on y is very slow

dragControls.addEventListener ( 'drag', function( event ){
 console.log('drag');
 event.object.position.y = 0; 
})

This seems to be what I was looking for. However, I want to move only along the Z-axis. Does Drag Controls not work along the Z-axis? If I put

event.object.position.y = 0;
event.object.position.x = 0;

It does not move at all. If I just use one of those it will move fine along either the X or Y axis.

Can you please share a simple fiddle or have any example created, of the same. I don’t have any idea on how to implement it.