I'm having issues with implementing multiple selection of three.js objects using CTRL-click. While single-select works perfectly, the behavior is problematic when trying to select multiple objects with CTRL-click. The selected array sometimes contains duplicate entries, and not every item in the array has the transformation applied consistently. It's quite confusing as the results are not what I expected. I suspect the problem lies within my logic statement inside the
if ( event.type === 'click' && event.ctrlKey )
block in the mouseEventHandler()
function, but I can't seem to pinpoint the exact mistake.
Below is the relevant code snippet:
var ray = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var INTERSECTED; // Object closest to the camera
var SELECTED = []; // Objects selected via dblclick
function onMouse( event ) {
event.preventDefault();
// Calculate mouse position in normalized device coordinates (-1 to +1) for both components
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
mouseEventHandler( event );
}
function mouseEventHandler( event /* , fn, revFn */ ){
// Update the picking ray with the camera and mouse position
ray.setFromCamera( mouse, entities.cameras.perspCamera );
// Calculate objects intersecting the picking ray
var intersects = ray.intersectObjects( scene.children );
// If there's at least one intersected object...
if ( intersects && intersects[0] && intersects[0].object ){
// Check various scenarios based on the type of event
// interaction with the intersected objects
}
}
// Additional functions for transforming graph elements based on mouse events
function transformGraphElementOnMouseOver( obj ){
if ( obj.isGraphElement ) { obj.referent.transformOnMouseOver(); }
}
function unTransformGraphElementOnMouseOut( obj ){
if ( obj.isGraphElement ) { obj.referent.transformOnMouseOut(); }
}
function transformGraphElementOnSelect( obj ){
if ( obj.isGraphElement ) { obj.referent.transformOnDblClick(); }
}
function unTransformGraphElementOnUnselect( obj ){
if ( obj.isGraphElement ) { obj.referent.unTransformOnDblClickOutside(); }
}
function transformGraphElementOnWheel( obj ){
if ( obj.isGraphElement ) { obj.referent.transformOnWheel(); }
}
// Event listeners setup
function listenFor(){
document.getElementById('visualizationContainer').addEventListener( 'click', onMouse, false );
document.getElementById('visualizationContainer').addEventListener( 'mousemove', onMouse, false );
document.getElementById('visualizationContainer').addEventListener( 'mousedown', onMouse, false );
document.getElementById('visualizationContainer').addEventListener( 'dblclick', onMouse, false )
document.getElementById('visualizationContainer').addEventListener( 'wheel', onMouse, false );
document.getElementById('visualizationContainer').addEventListener( 'contextmenu', onMouse, false );
}
listenFor();