Currently working on a 2D CAD drawing viewer using the three.js library. I need the ability to click on objects within the scene to perform operations.
However, when utilizing an orthographic camera, I've noticed that the precision of the three.js raycasting is not up to my expectations.
Check out the code and demo here: 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';
}
If you move your mouse near the red square, you'll notice that the intersection triggers before actually hovering over the edge.
I'm trying to figure out what might be causing this issue. Any ideas or suggestions?