我想为对象设置不同的颜色,这是我在Three JS中选择的。我得到了鼠标的x和y位置,但是函数raycaster.intersectObjects()总是返回一个空数组。
我在这里加载数据并填充对象数组:
var objects = [];
var mousev,raycaster, scene, renderer, controls, loader;
//Load Data
loader = new THREE.ObjectLoader();
loader.load("models/selectableObjects.json", function (obj) {
scene.add(obj);
scene.traverse(function(children){
objects.push(children);
});
},
function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
function (err) {
console.error('An error happened');
}
);
那是我的鼠标按下事件监听器:
raycaster = new THREE.Raycaster();
mousev = new THREE.Vector2();
document.addEventListener('mousedown', onDocumentMouseDown, false);
function onDocumentMouseDown(event){
event.preventDefault();
mousev.x = (event.clientX / renderer.domElement.width) * 2 - 1;
console.log("Mouse position X: "+mousev.x);
mousev.y = (event.clientY / renderer.domElement.height) * 2 + 1;
console.log("Mouse position Y: "+mousev.y);
raycaster.setFromCamera( mousev, camera );
var intersects = raycaster.intersectObjects( objects );
console.log("Objects: ");
console.log(objects);
console.log("Intersects: ");
console.log(intersects);
var color = (Math.random() * 0xffffff);
for ( var i = 0; i < intersects.length; i++ ) {
intersects[i].object.material.color.set( 0xff0000 );
}
}
谢谢您的帮助。