Search code examples
three.jscollada

collada 3D object mouse event



Hello all,

I wnat to change color on 3D object(collada file) child when the mouse over.
I try to use Raycaster method, but it doesn't work.
like this sample.
but i want to change color or highlight a model child when the mouse over.

and this is my code.

                var oLoader = new THREE.ColladaLoader();
                oLoader.load('model/sample.dae', function (collada) {

                    var object = collada.scene;
                    var skin = collada.skins[0]; 

                    object.rotation.x = -Math.PI / 2;
                    object.rotation.z = Math.PI / 2;
                    object.position.x = 0;
                    object.position.y = 0;
                    object.position.z = 0;
                    object.scale.set(0.025, 0.025, 0.025);
                    object.updateMatrix();
                    scene.add(object);

please tell me how to do.
Thanks very well.


Solution

  • coincidentally, i'm also working on a project requiring mouse events, and coded a small object to use.

    var mouse = {
        getIntersects: function( camera, sceneChildren, event ){
            event = event || window.event;
    
            var mouseX = ( event.clientX / window.innerWidth ) * 2 - 1;
            var mouseY = -( event.clientY / window.innerHeight ) * 2 + 1;
    
            var vector = new THREE.Vector3( mouseX, mouseY, camera.near );
                vector.unproject( camera );
    
            var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
    
            var intersects = raycaster.intersectObjects( sceneChildren );
    
            if ( intersects.length > 0 ) {
                //console.log(intersects);
                return intersects;
            }
            return false;
        },
    
        Position3D: function(sceneChildren){
            var intersects = mouse.getIntersects( sceneChildren );
            return intersects[0].point
        }
    }
    

    i dont know if you want to use this object on its own, or use it as a reference to code something yourself, but here's how you use it:

    document.addEventListener('click', function(event){
        var intersectObj = mouse.getIntersects( camera, scene.children, event)[0];
        if(window.console){ 
            console.log(intersectObj);
        }
        else{
            alert(intersectObj);
        }
    });
    

    now that you have the clicked object all sorted out, you can get started on the functions. The simplest way is to just add them to the mesh. so:

    var mesh = new THREE.Mesh(geometry, material);
        mesh.click = function(){
            alert('object was clicked');
        }