我正在尝试使用raycaster来使对象变得可点击。我已经看过无数的例子,我已经多次尝试过这段代码而没有运气。我在我的例子和我遇到的其他例子之间看到的唯一区别是我在一个球体内。
我通过创建一些变量来启动我的代码(有些变量可能不是使用过去的例子)。
var container, stats;
var camera, controls, scene, renderer, projector;
var isUserInteracting = false;
var mouse = { x: 0, y: 0, z: 0 }, intersected;
var fov = 70,
texture_placeholder,
isUserInteracting = false,
onMouseDownMouseX = 0, onMouseDownMouseY = 0,
lon = 0, onMouseDownLon = 0,
lat = 0, onMouseDownLat = 0,
phi = 0, theta = 0;
init();
animate();
我继续设置我的init()函数,我设置了一个摄像头并创建了我的球体。
function init() {
var container, mesh1;
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( fov, window.innerWidth / window.innerHeight, 1, 1100 );
camera.target = new THREE.Vector3( 0, 0, 0 );
scene = new THREE.Scene();
projector = new THREE.Projector();
mesh1 = new THREE.Mesh( new THREE.SphereGeometry( 500, 60, 40 ), new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( "spherical_map_small.jpg" )} ) );
mesh1.scale.x = -1;
mesh1.side = THREE.DoubleSide;
scene.add( mesh1 );
仍然在init()函数中,我创建了一个立方体几何体(这就是我想要点击的东西)。
meshMaterial = new THREE.MeshBasicMaterial({ color: 0x33CC00});
var geometry = new THREE.CubeGeometry( 20, 20, 20 );
var object = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { color: 0x33CC00} ) );
object.position.x = 75;
object.position.y = 10;
object.position.z = 0;
object.rotation.y = 45;
scene.add( object );
objects.push( object );
仍然在init()中,我设置了渲染器,并添加了一些事件侦听器。
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener( 'mouseup', onDocumentMouseUp, false );
document.addEventListener( 'mousewheel', onDocumentMouseWheel, false );
document.addEventListener( 'DOMMouseScroll', onDocumentMouseWheel, false);
//
window.addEventListener( 'resize', onWindowResize, false );
现在问题。接下来是应该让我的盒子“对象”的功能。可点击,似乎不起作用。我相信我告诉它说"有效。"每次单击场景中的对象时。
我已经阅读了关于使用three.js几个小时的光线投射,并且相信我对它应该如何工作有一个很好的理解,我无法让它工作。
function onDocumentMouseUp( event ) {
isUserInteracting = false;
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
var vector = new THREE.Vector3( mouse.x, mouse.y, .5 );
var raycaster = new THREE.Raycaster();
raycaster.setFromCamera(vector, camera);
var intersects = raycaster.intersectObjects(scene, true);
if ( intersects.length ) {
alert('works.');
}
}
任何帮助将不胜感激。谢谢。
答案 0 :(得分:0)
只是一个想法,尝试使用:
raycaster.intersectObjects(scene.children, true);
你设置递归(真)?否则它不会检查后代