在三个js中使用鼠标悬停更改网格的颜色

Change color of mesh using mouseover in three js

本文关键字:悬停 鼠标 网格 颜色 三个 js      更新时间:2023-09-26

我已经整理了一个WebGL脚本,它使用jsonloader和三个网格显示多个网格.js我现在想要添加MouseOver和onClick事件。其中第一个只是在鼠标悬停在网格上时更改网格的颜色:

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);
}

上面的渲染函数允许我将鼠标悬停在任何网格上将任何网格的颜色更改为红色。我已经尝试了几种 if/else 变体来尝试让这种效果仅在鼠标位于网格上时才起作用,但我无法让它工作 - 它只是保持红色。谁能建议我如何修改我的剧本?

谢谢。

您必须在

鼠标输出时将颜色设置回原始颜色,这不会自动发生......

检查此示例,特别是 http://stemkoski.github.io 更新方法:

这里有一个小提琴,演示更新到最新的三.js大师:

// 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;
}

由于上面答案中的代码已经过时(我试过了)...你可以看看threex.domevents library。它在我的情况下起到了作用。

threex.domevents 是一个三.js扩展,可在 3D 场景中提供 DOM 事件。始终努力与平时保持密切联系 实践中,事件名称与DOM中相同。语义是 同样,这使得这一切都很容易学习。目前, 可用事件包括单击、dblclick、鼠标向上、鼠标向下、鼠标悬停 并拔出鼠标。

下面是使用它的示例:

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