Event handling for geometries in Three.js?

柔情痞子 提交于 2019-12-07 17:47:29

问题


I am looking for some kind of event handling for geometries/cameras/lights(things we add to scene) in three.js ?

I googled but couldn't find anything relevant. I did a simple Sphere rendering and tried to see the DIV contents in firebug, but there's just one canvas, and adding any "onclick" to the canvas makes the event for all the canvas, that is, its not just for the sphere or light.

Any suggestions ?


回答1:


You need to a couple o things to get interactivity in 3D:

  1. get a vector for the mouse position
  2. unproject the mouse vector based on the camera
  3. shot a ray from the camera position, towards the unprojected mouse vector
  4. check what object(s) interesect with that ray and update accordingly.

It might sound complicated, but the code's already there:

function onDocumentMouseDown( event ) {

                event.preventDefault();

                var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
                projector.unprojectVector( vector, camera );

                var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );

                var intersects = ray.intersectObjects( objects );

                if ( intersects.length > 0 ) {

                    intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );

                    var particle = new THREE.Particle( particleMaterial );
                    particle.position = intersects[ 0 ].point;
                    particle.scale.x = particle.scale.y = 8;
                    scene.add( particle );

                }

                /*
                // Parse all the faces
                for ( var i in intersects ) {

                    intersects[ i ].face.material[ 0 ].color.setHex( Math.random() * 0xffffff | 0x80000000 );

                }
                */
            }

This code above from the canvas_interactive_cubes example that comes with the library. When in doubt, it's always good to check if there's an example that solves the problem already.



来源:https://stackoverflow.com/questions/9145383/event-handling-for-geometries-in-three-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!