Three.js投射光线实现三维物体交互
import * as THREE from 'three';
// 初始化场景、相机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建三维物体
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshNormalMaterial();
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// 添加光源
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 0.5).normalize();
scene.add(directionalLight);
// 创建投射器
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
function onMouseClick(event) {
// 将鼠标位置转换成归一化设备坐标(-1 到 +1)
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
// 使用摄像机和鼠标位置更新射线
raycaster.setFromCamera(mouse, camera);
// 计算物体和射线的交点
const intersects = raycaster.intersectObjects(scene.children);
if (intersects.length > 0) {
// 如果有交点,输出交点物体的名字
console.log('Clicked object:', intersects[0].object.name);
}
}
// 监听鼠标点击事件
window.addEventListener('click', onMouseClick, false);
// 渲染循环
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
这段代码初始化了一个Three.js场景,创建了一个立方体,并设置了光源和投射器。然后,它监听鼠标点击事件,并使用投射器计算鼠标点击位置的射线与场景中的物体的交点。如果存在交点,它会输出被点击的物体的名字。这个例子展示了如何在Three.js中实现鼠标与三维物体的交互。
评论已关闭