Change grid color with the mouse in three js

I have compiled a WebGL script that displays multiple grids using jsonloader and three.js, and now I want to add MouseOver and onClick events. The first one is just a change in the color of the grid when the mouse hangs over it:

function render() {
  requestAnimationFrame(render);    
  mesh.rotation.z += 0.090;    
  raycaster.setFromCamera(mouse, camera);    
  var intersects = raycaster.intersectObjects(scene.children);  

  for (var i = 0; i < intersects.length; i++) {    
    intersects[i].object.material.color.set(0xff0000);    
  }    
  renderer.render(scene, camera);

}

The rendering function above allows me to change the color of any mesh to red, hanging over it. I tried several if / else options to try, and this effect only works when the mouse is over the grid, but I can’t get it to work - it just stays red. Can anyone suggest how I can change my script?

Thank.

+4
source share
2 answers

, ...

http://stemkoski.imtqy.com , :

- ​​ . 3. :

// create a Ray with origin at the mouse position
//   and direction into the scene (camera direction)
var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
projector.unprojectVector( vector, camera );
var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );

// create an array containing all objects in the scene with which the ray intersects
var intersects = ray.intersectObjects( scene.children );

// INTERSECTED = the object in the scene currently closest to the camera 
//      and intersected by the Ray projected from the mouse position    

// if there is one (or more) intersections
if ( intersects.length > 0 )
{
    // if the closest object intersected is not the currently stored intersection object
    if ( intersects[ 0 ].object != INTERSECTED )
    {
        // restore previous intersection object (if it exists) to its original color
        if ( INTERSECTED )
            INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
        // store reference to closest object as current intersection object
        INTERSECTED = intersects[ 0 ].object;
        // store color of closest object (for later restoration)
        INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
        // set a new color for closest object
        INTERSECTED.material.color.setHex( 0xffff00 );
    }
}
else // there are no intersections
{
    // restore previous intersection object (if it exists) to its original color
    if ( INTERSECTED )
        INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
    // remove previous intersection object reference
    //     by setting current intersection object to "nothing"
    INTERSECTED = null;
}
+9

( ), trx.domevents library, .

threex.domevents - three.js, 3D-. pratices, DOM. - , . , dblclick, mouseup, mousedown, mouseover .

, :

http://bl.ocks.org/fabiovalse/2e8ae04bfce21af400e6

+1

All Articles