提问人:sunShine 提问时间:11/2/2023 最后编辑:sunShine 更新时间:11/3/2023 访问量:45
如何使用Orbitcontrol在Threejs中为点击的网格着色?
How to color the clicked mesh in Threejs using Orbitcontrol?
问:
我正在尝试在 ThreeJs 的网格组中为单击的网格着色。此外,我正在将 orbitcontrol 用于 3D 模型。但是当我尝试为点击的网格着色时,一个不同的网格被着色了。
这是我的代码的一部分:
lines.forEach(line => {
const values = line.split('\t'); // tab separated
if (values.length === 3) {
const x = parseFloat(values[0]);
const y = parseFloat(values[1]);
const z = parseFloat(values[2]);
const sphere = new THREE.Mesh(geometry, defaultMaterial.clone());
switch (currentAxis) {
case 'x':
sphere.position.set(x, 0, 0);
break;
case 'y':
sphere.position.set(0, y, 0);
break;
case 'z':
sphere.position.set(0, 0, z);
break;
default:
sphere.position.set(x, y, z);
break;
}
scene.add(sphere);
spheres.push(sphere);
}
});
renderer.domElement.addEventListener('click', onCanvasClick, false);
function onCanvasClick(event) {
// Calculate the mouse click position in normalized device coordinates (NDC)
var mouse = new THREE.Vector2();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// Raycasting is used to determine which object was clicked
var raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(spheres);
if (intersects.length > 0) {
// Check if the clicked mesh is different from the previously clicked mesh
if (intersects[0].object !== clickedMesh) {
// Reset the color of the previously clicked mesh (if any)
if (clickedMesh) {
clickedMesh.material.color.set(0xffffff); // Reset to the original color
}
// Change the color of the clicked mesh
intersects[0].object.material.color.set(0x0000ff);
clickedMesh = intersects[0].object; // Update the currently clicked mesh
}
}
}
我使用了 Raycaster,但不幸的是,它还没有工作。如何仅对点击的网格进行着色?
编辑:
当我像这样更改 x,y 时:
const containerRect = container.getBoundingClientRect();
const x = ((event.clientX - containerRect.left) / container.clientWidth) * 2 - 1;
const y = -((event.clientY - containerRect.top) / container.clientHeight) * 2 + 1;
它开始离得太近了。当我放大模型时,找到正确网格的概率大大增加,但随着模型的移动距离越来越远,它离正确的网格越来越远。
一些信息:
const container = document.querySelector('.design');
// Create a camera with appropriate aspect ratio and size
const width = container.clientWidth;
const height = container.clientHeight;
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
const CAM_DISTANCE = 10;
答: 暂无答案
评论
OrbitControls
与检测鼠标下方的内容没有任何关系。更深入地查看三个 .js 文档和示例,了解如何使用以及它返回的内容。Mesh
Raycaster