Mar*_*man 8 javascript three.js raycasting
我已经整理了一个使用jsonloader和three.js显示多个网格的WebGL脚本,现在我想添加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);
}
Run Code Online (Sandbox Code Playgroud)
上面的渲染功能允许我将任何网格的颜色悬停在它上面.我已经尝试了几个if/else变体尝试并且只有在鼠标悬停在网格上时才能使用此效果,但我无法使其工作 - 它只是保持红色.任何人都可以建议我如何修改我的脚本?
谢谢.
Wil*_*ilt 12
您必须在鼠标输出时将颜色设置回原始颜色,这不会自动发生...
请在http://stemkoski.github.io上查看此示例,具体是更新方法:
这里有一个演示小提琴更新到最新的three.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;
}
Run Code Online (Sandbox Code Playgroud)
由于上面答案中的代码已过时(我尝试过)...您可以查看Threex.domevents 库。它在我的例子中发挥了作用。
Threex.domevents 是一个 Three.js 扩展,它在 3D 场景中提供 dom 事件。为了始终保持接近惯例,事件名称与 DOM 中的名称相同。语义也相同,这使得一切都非常容易学习。目前,可用的事件有 click、dblclick、mouseup、mousedown、mouseover 和 mouse out。
这是一个使用它的示例:
http://bl.ocks.org/fabiovalse/2e8ae04bfce21af400e6
| 归档时间: |
|
| 查看次数: |
10647 次 |
| 最近记录: |