Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

javascript - three.js - get object name with mouse click

I had loaded 3 external model with the name into my scene using json loader and now i want to get the name of the model/object by clicking it.

Below is the that i had used to load the model

var object_material = new THREE.MeshBasicMaterial({                 
                    color: 0xd6d6d6,                            
                    side: THREE.DoubleSide          
                });

    var   loader = new THREE.JSONLoader();
    loader.load("models/"+file,
                    function(geometry, object_material) 
                    {   

            var object = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(object_material));             

                        model = new THREE.Object3D();
                        model.id=file;
                        model.name='sample'+file;
                        model.userData.id='sampledata'+file;
                        model.add(object);    
                        model.position.set(obj_x,obj_y,obj_z);                                                  

                        model.mirroredLoop = true;
                        model.castShadow = true;
                        model.receiveShadow = true;         

                        scene.add(model);

                    }
                );  

Below is my mouse down function

function onMouseDown(event) {

    event.preventDefault();

    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

    var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
    projector.unprojectVector( vector, camera );


        var pLocal = new THREE.Vector3(0, 0, -1);
        var pWorld = pLocal.applyMatrix4(camera.matrixWorld);
        var ray = new THREE.Raycaster(pWorld, vector.sub(pWorld).normalize());
        // Get meshes from all objects
        var getMeshes = function(children) {
            var meshes = [];
            for (var i = 0; i < children.length; i++) 
            {
                if (children[i].children.length > 0) {
                    meshes = meshes.concat(getMeshes(children[i].children));
                } else if (children[i] instanceof THREE.Mesh) {
                    meshes.push(children[i]);
                }
            }
            return meshes;
        };
        function attributeValues(o) 
        {
            var out = [];
            for (var key in o) {
            if (!o.hasOwnProperty(key))
            continue;
            out.push(o[key]);
            }
            return out;
        }
        var objects = attributeValues(this.o3dByEntityId);
        var meshes = getMeshes(objects);

    var intersects = ray.intersectObjects(meshes);      
    raycaster.set( camera.position, vector.sub( camera.position ).normalize() );
    var intersects = raycaster.intersectObjects( scene.children );

    console.log(scene);
    // this console displays all the objects under children - THREE.Object3D - name as name: "sample513.js" 

    if ( intersects.length > 0 )
    {
        // but for the clickedObject - the length is > 0 and name is empty
        var clickedObject = intersects[0].object;
        console.log(clickedObject.parent.userData.id); // return as undefined

        if ( INTERSECTED != intersects[ 0 ].object )
        {                               
            INTERSECTED= intersects[ 0 ].object;                
            name    =   INTERSECTED.name;                       
        }

    } else {

        console.log('intersects.length is 0');

    }
}

Even-though i had provided the model name in the userData , i am not able to retrieve it . can any one guide me how to retrieve the name of the object when it is clicked

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try to make through this example. Look at messages in the console.

<script src="js/controls/EventsControls.js"></script>

EventsControls = new EventsControls( camera, renderer.domElement );

EventsControls.attachEvent( 'onclick', function() {

    console.log( 'this.focused.name: ' + this.focused.name );

});

// if use drag and drop

EventsControls.attachEvent( 'dragAndDrop', function () {

    this.container.style.cursor = 'move';
    this.focused.position.y = this.previous.y;

});

EventsControls.attachEvent( 'mouseOut', function () {

    this.container.style.cursor = 'auto';

});

var jsonLoader = new THREE.JSONLoader();
jsonLoader.load( "models/Tux.js", addModelToScene ); 


function addModelToScene( geometry, materials ) {

   var material = new THREE.MeshFaceMaterial( materials );
   model = new THREE.Mesh( geometry, material );
   model.scale.set( 10, 10, 10 ); model.name = 'Tux';
   model.rotation.x = -Math.PI/2; 
   model.position.set( 175, 45, 125 );
   scene.add( model ); 
   EventsControls.attach( model );

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...