用于物体的拾取和页面事件的交互
// 创建多个立方体
const cubeGeometry = new THREE.BoxBufferGeometry(1,1,1);
const material = new THREE.MeshBasicMaterial({
wireframe:true
});
const redmaterial = new THREE.MeshBasicMaterial({
color:"#ff0000"
})
const cubeArr = [];
for(let i=0;i<10;i++){
const cube = new THREE.Mesh(cubeGeometry,material);
cube.position.set(i,i,0)
scene.add(cube)
cubeArr.push(cube)
}
// 创建投射光线对象
const raycaster = new THREE.Raycaster();
// 鼠标的位置对象
const mouse = new THREE.Vector2();
// 监听鼠标的位置
window.addEventListener("click",(event)=>{
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -((event.clientY / window.innerHeight) * 2 - 1);
raycaster.setFromCamera(mouse,camera);
// intersectObjects 检测多个物体
let result = raycaster.intersectObjects(cubeArr)
console.log(result)
result[0].object.material = redmaterial
})