gpt4 book ai didi

javascript - three.js 中使用正交相机的不精确光线转换

转载 作者:行者123 更新时间:2023-11-29 20:37:39 25 4
gpt4 key购买 nike

我正在使用 three.js 库开发 CAD 绘图的二维查看器,对于这个项目,我需要能够单击场景中的对象来执行一些操作。

使用正交相机,three.js 光线转换并不像我预期的那样精确。

这里的代码和一个 fiddle 正好显示了我的意思 https://jsfiddle.net/toriphes/a0o7td1u/

var camera, scene, renderer, square, raycaster;
init();
animate();

function init() {

output = document.getElementById('output');

raycaster = new THREE.Raycaster();
// Renderer.
renderer = new THREE.WebGLRenderer();
//renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
// Add renderer to page
document.body.appendChild(renderer.domElement);

// Create camera.
var aspect = window.innerWidth / window.innerHeight;
var d = 20;
camera = new THREE.OrthographicCamera(-window.innerWidth / 2, window.innerWidth / 2, window.innerHeight / 2, -window.innerHeight / 2, 1, 1000);
camera.position.z = 10;
camera.position.x = 25;
camera.position.y = 25;
camera.zoom = 10
camera.updateProjectionMatrix()

controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableRotate = false
controls.target.x = camera.position.x;
controls.target.y = camera.position.y;

controls.update();


// Create scene.
scene = new THREE.Scene();

var points = [
new THREE.Vector2(10, 10),
new THREE.Vector2(40, 10),
new THREE.Vector2(40, 40),
new THREE.Vector2(10, 40),
new THREE.Vector2(10, 10)
]

var shape = new THREE.Shape(points);

var geometry = new THREE.Geometry().setFromPoints(points);

var square = new THREE.Line(geometry, new THREE.LineBasicMaterial({
color: 0xFF0000
}));
scene.add(square)

document.addEventListener('mousemove', findIntersections, false);
}

function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}

function updateMousePosition(event) {
return new THREE.Vector3(
(event.clientX - renderer.domElement.offsetLeft) /
renderer.domElement.clientWidth *
2 -
1,
-(
(event.clientY - renderer.domElement.offsetTop) /
renderer.domElement.clientHeight
) *
2 +
1,
0
);
}

function findIntersections(e) {
var mouseposition = updateMousePosition(e);
raycaster.setFromCamera(mouseposition, camera);
const intersects = raycaster.intersectObjects(scene.children);
output.innerHTML = intersects.length > 0 ?
'Intersect: TRUE' :
'Intersect: FALSE';
}

如果您将鼠标经过红色方 block 附近,您可以看到交叉点在悬停边缘之前触发。

我做错了什么?

最佳答案

线的交点检测依赖于.linePrecision Raycaster 的属性(property).

例如

raycaster.linePrecision = 0.1;
const intersects = raycaster.intersectObjects(scene.children);

必须根据场景的比例设置参数。 0.1 的值是一个经验值,它为您的示例提供了良好的结果。遗憾的是,文档中没有提供更多信息(也许我忽略了什么,但我没有找到)。

关于javascript - three.js 中使用正交相机的不精确光线转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56349097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com