How can a Raycaster be utilized to retrieve the intersection coordinates from the perspective of the player's viewpoint?

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);
}

Answer №1

After examining this particular example script, I was able to figure it out.

Now I have implemented a feature that allows me to shoot a ray from the camera's position in the direction that the player/camera is facing:

var raycaster = new THREE.Raycaster();
var direction = new THREE.Vector3( 0, 0, -1 );
var rotation = new THREE.Euler( 0, 0, 0, "YXZ" );

function shootRay() {
    rotation.set( pitchObject.rotation.x, yawObject.rotation.y, 0 );

    raycaster.ray.direction.copy( direction ).applyEuler( rotation );
    raycaster.ray.origin.copy( yawObject.position );

    var intersections = raycaster.intersectObjects( groupedMeshes );
    if ( intersections.length > 0 ) {
        console.log(intersections[0].point);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery dialog to load a form through AJAX and then submitting the form to the modal dialog

I have adapted pieces of code from various sources to create the following script. The links successfully load the edit form in a modal using ajax, but upon submitting the form, the entire page refreshes instead of just the modal. I am seeking a solution ...

Changing the URL for the onClick event of a button in Laravel through AJAX

I am working on a basic form that includes a "Submit" button and an extra "Add" button in a blade template. When the form is submitted, there is an ajax call to a controller for validation of the provided value. Depending on the response from the controlle ...

jQuery input checkboxes validation conflict

There seems to be a strange issue with my checkboxes in the table where I have built an Invoice calculator. You can view it here. My goal is to have the inputs for Iva or Irpef not calculated in the Total Amount once they are checked. In the linked example ...

Getting your JQuery ready() statement right is crucial for the proper

I have come across all three variations below: $().ready(); $(document).ready(); $(document.body).ready(); All of them seem to work, but I'm wondering which one is the most appropriate or recommended to use when considering the usage of the ready() ...

what is the method to extract the value of a JSON object nested within another JSON object

Can someone please assist me? "_attachments": { "kiran.jpg": { "content_type": "image/jpeg", "revpos": 6, "digest": "md5-mEsoX4ljN1iJlF2bX1Lw2g==", "length": 4601, "stub": true } } I ...

Solving CORS policy errors in Dot Net Core Web API using Javascript

In my development environment, I am utilizing Visual Studio Code with liveserver for HTML and JavaScript, while also using Visual Studio 2019 for Dot Net Core Web API. I have set up the site in IIS on Windows 10 locally for the web API. My login functiona ...

Tips on effectively organizing information retrieved from an XML file?

I would like to organize the data in ascending order based on the DATE after making this ajax call function parseXML(xml){ var weatherArray = []; var weatherElement = xml.getElementsByTagName("forecast")[0]; weatherArray.queryTime = weatherEl ...

Problems encountered while invoking a function using ng-click within an AngularJS controller?

You can check out the code by visiting When attempting to login, I trigger the simple login() function of the AuthController using ng-click on the login form button. However, upon calling this function, I encounter an error message in the console that I a ...

Button Click Not Allowing Webpage Scroll

I am currently in the process of developing a website that aims to incorporate a significant amount of motion and interactivity. The concept I have devised involves a scenario where clicking on a button from the "main menu" will trigger a horizontal and ve ...

PHP MySQL - Automatically trigger email notification upon insertion of a new record

Is there a way to trigger an email alert only when a new record is added, not when the user edits input fields in a table? The database I'm working with stores equipment delivery dates. Users schedule deliveries and input the dates into a SQL Server ...

Connecting the search results page with the specific details page

Currently, I am developing a results page for my website and require assistance with linking each restaurant to a detail.php page. The project involves showcasing all the restaurants in San Francisco along with their health inspection scores, address, and ...

The jQuery remove function will only take effect on the second click following an AJAX request

I'm facing an issue with my jQuery code where two divs contain lists of links, triggering AJAX calls to append JSON data to a separate div. Upon clicking a link, the corresponding link div should hide. There's also a third div with the class "pan ...

Discovering the presence of a logo within an image using NodeJS

I'm currently investigating if it's possible to process an image on a nodeJS server to determine if it contains another image. For instance: Image 1: A picture of a laptop example: http://amasoncomputers.com/wp-content/uploads/2015/04/hp-630.jp ...

Tips for utilizing Vue router query parameters while in hash mode:

Is there a more efficient way to access URL parameters in Vue methodology, without having to rely on window.location.href and parsing the URL? router/index.js const router = new Router({ mode: 'hash', routes: [] }); router.beforeEach((to, f ...

Is it necessary to have NodeJs in order to host a React app on a server?

I've been working on a .NET Core 2.2 project with React integration, As I'm nearing completion of the project, I have a query that has been on my mind. Do I need Node.js installed on the server for React to function properly? Thank you. ...

The color of the button in HTML5 will remain constant and not shift

I have several buttons that function like radio buttons - only one can be selected at a time: <button id="btn-bronze" name="btn-bronze" type="button" class="blue-selected">Bronze</button> <button id="btn-silver" name="btn-silver" type="butt ...

Collecting all Material-UI components into a single document

Currently, I am engaged in a Meteor project that utilizes Material UI and ReactJS. I wish to streamline the process by creating a single file that imports all necessary Material UI components for my project. This way, instead of adding individual exports ...

Manipulating the DOM to show various elements upon clicking on text

Currently, I am engaged in a small project that involves experimenting with DOM manipulation. The project revolves around creating a Todo list where users can generate various categories (such as work, gym, finances, etc.) and then add corresponding subtas ...

Guide to adding a file upload progress bar to your website

Is there a way to enhance file upload experience on my web application beyond the usual animated gif? I'm currently using .Net, but open to platform agnostic solutions as well. ...

Using Google Maps: Dragging the marker constantly results in the same position being returned by GetPosition

I'm having an issue with a for loop that creates more than 100 markers. Every time I drag a random marker, the console logs the same position even though the "Point" value is different when dragging another marker. Why am I consistently getting the sa ...