Three.js 点击获取 Mesh 世界坐标:交互式 3D 场景示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Three.js 点击获取 Mesh 世界坐标:交互式 3D 场景示例</title>
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
window.addEventListener('DOMContentLoaded', init);
<pre><code> function init() {
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.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
const worldPosition = new THREE.Vector3();
function onMouseClick(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObject(cube);
if (intersects.length > 0) {
const point = intersects[0].point;
point.applyMatrix4(cube.matrixWorld);
console.log("Point in World Coordinate System:", point);
}
}
window.addEventListener('click', onMouseClick);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/pRip 著作权归作者所有。请勿转载和采集!