I am adding a small red sphere at the point of intersection.
You can see that it is getting offset by some distance, I have already applied the solution mentioned in this thread. Solution in a thread
Here is my code:
//
// Raycaster
//
let raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2()
window.addEventListener('mousemove', (event) => {
var canvasBounds = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - canvasBounds.left) / (canvasBounds.right - canvasBounds.left)) * 2 - 1;
mouse.y = - ((event.clientY - canvasBounds.top) / (canvasBounds.bottom - canvasBounds.top)) * 2 + 1;
})
let testBox = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), new THREE.MeshBasicMaterial);
testBox.position.set(-5, 5, 10);
testBox.name = 'Test Box'
scene.add(testBox)
//
// GAME LOOP ==========================================================================
//
const clock = new THREE.Clock();
let animate = () => {
...
...
raycaster.setFromCamera(mouse, camera)
let boxIntersect = raycaster.intersectObject(testBox);
console.log(boxIntersect);
if(boxIntersect.length > 0){
let sphereTest = new THREE.Mesh(new THREE.SphereGeometry(0.02, 32, 32), new THREE.MeshBasicMaterial({color:'red'}));
sphereTest.position.set(boxIntersect[0].point.x, boxIntersect[0].point.y, boxIntersect[0].point.z);
scene.add(sphereTest)
}
...
}
Not sure whats wrong in yr app… can you post the renderer setup? Are you setting devicePixelRatio? That might interact with the coordinate calculation…
//
// CAMERA =============================================================================
//
let camera;
let perspectiveCamera = new THREE.PerspectiveCamera(
55,
sizes.width / sizes.height,
0.1,
300
);
perspectiveCamera.position.set(-8, 8, 25);
camera = perspectiveCamera
There are a couple calls to .lookAt in the main loop. These are changing the camera transform, but not updating the cameras matrices. normally this isn’t a big deal since the renderer.render call updates them… but you happen to be doing your raycast after those .lookAts, but before renderer.render so the camera matrix the raycaster is using is stale.
you’re welcome! raycasting is often very fiddly to get right.
Throwing some:
.updateMatrix()
.updateMatrixWorld()
and scene.updateMatrixWorld( true )
before key operations can be a good sanity check when things are acting weird.