I'm encountering difficulties in determining the coordinates of where the player is looking in the game world using a Raycaster. The intersections are not being picked up successfully.
Specifically, I am attempting to retrieve the coordinates of the intersection on the terrain, which consists of multiple BufferGeometry meshes. Below is the code snippet that I am utilizing from the Raycaster example: (groupedMeshes
array holds the BufferGeometry meshes)
var mouseX = ( event.clientX / window.innerWidth ) * 2 - 1;
var mouseY = -( event.clientY / window.innerHeight ) * 2 + 1;
var vector = new THREE.Vector3( mouseX, mouseY, camera.near );
// Convert the [-1, 1] screen coordinate into a world coordinate on the near plane
var projector = new THREE.Projector();
projector.unprojectVector( vector, camera );
var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
// Check if the ray from the camera into the world intersects with any of our meshes
var intersects = raycaster.intersectObject( groupedMeshes );
lastIntersects = intersects;
if ( intersects.length > 0 ) {
console.log("Intersection!");
}
Additionally, an image illustrating the player's perspective:
(The red dot signifies my intention to cast a ray from the center of the camera to the terrain)
Since the mouse/pointer is locked (resulting in first-person camera view), I assume I should verify for an intersection at the center of the screen? Since the provided code does not achieve this, I have been conducting tests without locking the pointer.
If anyone can identify why no intersections are being detected, your assistance would be greatly appreciated. Thank you.
EDIT:
It appears that I should be using
raycaster.intersectObjects( groupedMeshes );
instead of raycaster.intersectObject( groupedMeshes );
. My mistake.
Therefore, my current inquiry revolves around how to project the ray from the player's first-person view to the terrain. Much obliged!
EDIT2:
var vector = new THREE.Vector3( 0, 0, 0.5 );
var projector = new THREE.Projector();
projector.unprojectVector( vector, camera );
var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
var intersects = raycaster.intersectObjects( groupedMeshes );
lastIntersects = intersects;
if ( intersects.length > 0 ) {
console.log(intersects);
}