Three.js provides powerful add-ons like OrbitControls and DragControls to enhance user interaction with your 3D scenes. These controls are not part of the core Three.js library and need to be imported separately.
OrbitControls allow the camera to orbit around a target point in the 3D scene. This is incredibly useful for exploring a scene from different angles, allowing users to rotate, pan, and zoom the camera.
You create an instance of OrbitControls by passing the camera object and the HTML DOM element (usually the renderer's canvas) for event listeners. The controls need to be updated in the animation loop.
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // an animation loop is required when damping is enabled
controls.dampingFactor = 0.25;
controls.screenSpacePanning = false;
controls.maxPolarAngle = Math.PI / 2;
function animate() {
requestAnimationFrame(animate);
controls.update(); // only required if controls.enableDamping or controls.autoRotate are set to true
renderer.render(scene, camera);
}
DragControls enable drag-and-drop interaction for 3D objects within the scene. This allows users to directly manipulate objects by dragging them with the mouse.
To use DragControls, you need to provide an array of draggable 3D objects, the camera, and the DOM element. Event listeners can be added for dragstart and dragend events to perform actions when an object is being dragged or dropped.
import { DragControls } from 'three/examples/jsm/controls/DragControls.js';
const objects = [cube, sphere]; // Array of objects to make draggable
const dragControls = new DragControls(objects, camera, renderer.domElement);
dragControls.addEventListener( 'dragstart', function ( event ) {
event.object.material.emissive.set( 0xaaaaaa );
} );
dragControls.addEventListener( 'dragend', function ( event ) {
event.object.material.emissive.set( 0x000000 );
} );
It is possible to use both OrbitControls and DragControls in the same scene. However, potential conflicts can arise, as both might try to handle mouse events simultaneously. A common approach to mitigate this is to disable OrbitControls when an object is being hovered over or dragged by DragControls.
This example demonstrates a scene where you can orbit the camera around a cube and also drag the cube around.