Utilizing Three.js to employ raycasting from the camera in order to choose specific items

Hi everyone, I'm currently attempting to create a ray that extends straight out from the camera and intersects with objects in my line of sight. However, all the resources I've come across involve using the mouse for this interaction, and I'm struggling to adapt it.

This is the code I've managed to put together:

var raycaster = new THREE.Raycaster();

function render() 
{ 
    raycaster.set(camera, 0);

    renderer.render( scene, camera );
}

Answer №1

I implemented a similar solution using the mouse position instead of the camera.

var x = (event.offsetX / renderer.domElement.width) * 2 - 1;
var y = -(event.offsetY / renderer.domElement.height) * 2 + 1;
var z = 0.5;
var mousePosition = new THREE.Vector3(x, y, z);
var raycaster = new THREE.Raycaster();

mousePosition.unproject(camera);
raycaster.set(camera.position, mousePosition.sub(camera.position).normalize());

var intersectObjects = raycaster.intersectObjects(scene.children);

if (intersectObjects.length) {
    // do something
}

You might consider replacing the first two lines, event.offsetX and event.offsetY, with the center of your canvas like:

var x = ((canvasElement.clientWidth / 2) / renderer.domElement.width) * 2 - 1;
var y = -((canvasElement.clientHeight / 2) / renderer.domElement.height) * 2 + 1;

UPDATE: Now you can implement special actions with the intersected cube. For instance, display its wireframes like:

intersectObjects[0].material.wireframe = true
.

NOTE: The intersectObjects array is sorted by distance, so the closest object will be at index 0.

.

UPDATE #2: You could create an "update loop" with an update() function to utilize the above code. Here are two methods to achieve this:

  • use setInterval(update, 1000 / 60): 1000 / 60 ensures it is called 60 times per second. Drawback: imprecision if the update function takes longer than 16.6 milliseconds (1000 / 60).
  • Invoke the update method within your render function. Benefit: greater precision and separation of application logic from rendering.

    function update() { // insert code here }

    function render() { // ... update(); }

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

Encountering a problem with Axios get request error in React and Redux when communicating with a Laravel 5.2 API

Currently, I am utilizing react alongside redux and axios for handling asynchronous actions. The backend is powered by Laravel 5.2 API which is located on a subdomain, while React resides on the main domain. However, whenever I attempt to make an async GET ...

Issue with Google Charts where the label does not show outside of the bar if the bar is too small

I am encountering an issue with my Google Bar Chart where the bar label is not displaying outside of the bar when it is too large to fit inside. This behavior should be the default, but my charts are not working as expected. The problem can be seen in rows ...

What is the reason behind this build error I am encountering while using react-three-xr?

I'm having trouble understanding this error message. What steps can I take to resolve it? Although I have included three-xr in my react app, I am encountering the following error: Failed to compile. ../../node_modules/@react-three/xr/src/DefaultXRCon ...

Having trouble with Angular 2 and localhost/null error while attempting to make an http.get request?

In my Angular 2 webpage, I am using the OnInit function to execute a method that looks like this (with generic names used): getAllObjects(): Promise<object[]>{ return this.http.get(this.getAllObjectsUrl).toPromise().then(response => response. ...

Obtain keys from an object implemented with an interface in TypeScript

Is it possible to retrieve the actual keys of an object when utilizing an interface to define the object? For example: interface IPerson { name: string; } interface IAddress { [key: string]: IPerson; } const personInAddressObj: IAddress= { so ...

Tips for enforcing validation rules at the class level using Angular's version of jQuery Validate

After utilizing jQuery Validate's convenient addClassRules function to impose a rule on all elements of a specific class, rather than relying on the attributes of their name, I encountered a roadblock when trying to do the same with the Angular wrappe ...

JavaScript: what is the method to add a paragraph when the condition is not met?

I am currently working on a project that involves checking if a student is actively engaged in an online journal. This is done by tracking the student's progress using a unique userId. If the student's userId is not found in the JSON data returne ...

Sending data from a Node.js backend to a React.js frontend using res.send

How can I pass a string from my nodejs backend using res.send? app.post("/user", (req,res) => { console.log(req.body.email); res.send('haha'); }); I need to perform certain operations on the front end based on the value of the string retriev ...

Testing an ExpressJS route and their corresponding controller individually: a step-by-step guide

I have set up an Express route in my application using the following code snippet (where app represents my Express app): module.exports = function(app) { var controller = require('../../app/controllers/experiment-schema'); app.route('/a ...

Ways to retrieve the file name from the content-disposition header

I received a file through an AJAX response. I am trying to extract the filename and file type from the content-disposition header in order to display a thumbnail for it. Despite conducting multiple searches, I have been unable to find a solution. $(". ...

Upcoming construction: Issue encountered - The Babel loader in Next.js is unable to process .mjs or .cjs configuration files

Within my package.json file, I have set "type": "module" and "next": "^12.2.5". In my tsconfig.json: { "compilerOptions": { "target": "ES2022", "module": "esnext ...

Best practices for establishing a conditional statement with JQuery's inArray function

I am working on a code snippet to generate a list of unique random numbers. Each generated number is supposed to be added to an array after checking that it doesn't already exist in the array. However, I seem to be facing some challenges with getting ...

Steps to eliminate pre-chosen alternatives upon loading select control?

When using react-select with pre-selected options and multiple select enabled, the issue arises where clicking on the Select box still displays the already pre-selected options. How can I remove these duplicate options from the list? Below is a snippet of ...

During the deployment of a ReactJS app, webpack encounters difficulty resolving folders

While developing my ReactJS app, everything ran smoothly on localhost. However, I encountered some serious issues when I tried to deploy the app to a hosting service. In my project, I have a ./reducers folder which houses all of my reducers. Here is the s ...

"Utilizing JSON information to create visually appealing graphs and charts

Struggling with syntax and in need of assistance. I have a basic data set that I want to display as a timeline with two filled lines (Time Series with Rangeslider). This is the format of my data set: [{"pm10": 12.1, "pm25": 7.0, "time": "13.08.2018 12:25 ...

What sets apart the JavaScript console from simply right-clicking the browser and opting for the inspect option?

As I work on developing an angular application, one of my tasks involves viewing the scope in the console. To do this, I usually enter the code angular.element($0).scope(). This method works perfectly fine when I access the console by right-clicking on th ...

Having trouble getting my local website to load the CSS stylesheet through Express and Node.js in my browser

https://i.stack.imgur.com/qpsQI.png https://i.stack.imgur.com/l3wAJ.png Here is the app.js screenshot: https://i.stack.imgur.com/l3wAJ.png I have experimented with different combinations of href and express.static(""); addresses. However, I am ...

Did I incorrectly pass headers in SWR?

After taking a break from coding for some time, I'm back to help a friend with a website creation project. However, diving straight into the work, I've encountered an issue with SWR. Challenge The problem I'm facing is related to sending an ...

typescript throwing an unexpected import/export token error

I'm currently exploring TypeScript for the first time and I find myself puzzled by the import/export mechanisms that differ from what I'm used to with ES6. Here is an interface I'm attempting to export in a file named transformedRowInterfac ...

Ensuring the website retains the user's chosen theme upon reloading

I have been developing a ToDo App using MongoDB, EJS, and Node JS. My current challenge involves implementing a theme changer button that successfully changes colors when clicked. However, whenever a new item is added to the database, the page reloads caus ...