Selecting objects in Three.js using the camera but without using the mouse

I am working on a Three.js app where I need to determine the object that the perspective camera is focusing on. In order to achieve this, I consulted the raycaster documentation. Most of the resources I came across discuss using raycasting with a camera and Vector2 based on mouse coordinates. However, I do not want to rely on the 2D coordinates of the mouse for this purpose. The camera in my app can rotate due to various interactions such as clicking and dragging on the screen, touch controls, or even VR controls. What I specifically aim to do is perform a raycast from the center point of the perspective camera and highlight/select the object it is looking at.

Any advice or suggestions on how I can achieve this?

Answer №1

When using THREE.Raycaster.set(), make sure to provide both origin and direction vectors:

origin — This is the starting point from where the ray will be cast.

direction — Specify the vector that determines the direction of the ray. Remember, it should be normalized.

To set the world position of the cameras as the origin and its world direction as the direction:

var raycaster = new THREE.Raycaster();

raycaster.set( camera.getWorldPosition(), camera.getWorldDirection() );

var intersects = raycaster.intersectObjects( objectsArray );
if ( intersects.length > 0 ) {
    //...
}

Answer №2

Falk's code still functions, however, Three.js requires a target to be defined in versions greater than r90 [1]:

Now, the target is a mandatory requirement.

To implement this, follow these steps:

let camera_world_pos = new THREE.Vector3();
let camera_world_dir = new THREE.Vector3();
let raycaster = new THREE.Raycaster();

camera.getWorldPosition(camera_world_pos);
camera.getWorldDirection(camera_world_dir);
raycaster.set(camera_world_pos, camera_world_dir);
let intersects = raycaster.intersectObjects( objectsArray );
if ( intersects.length > 0 ) {
    //...
}

[1] https://github.com/mrdoob/three.js/issues/12231

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

Exploring the intricacies of logic through the interactive features of .hover and .click in tandem with Raphael

My goal is to create a hover effect and a click state for a specific area on a map. At present, I want one color to appear when hovering, and another color to display when clicked. Ideally, I'd like the click color to remain even after the user moves ...

Performing multiple SQL queries in a for loop using Node.js and Express

After submitting a Post form, I receive a req.body containing multiple values in the following format: console.log(req.body) { productid:[1, 2, 3] qty: [3, 5, 6] } I'm trying to implement a for loop to use these values in SQL queries. However, I e ...

Tips for retrieving data from a concealed input within a div that is being looped through in Angular.js

Currently, I have a controller that sends data to the UI and uses the ng-repeat directive to map them. My next goal is to bind this data with a hidden input form and then send it to another function in the controller when a click event occurs. Any tips on ...

The content inside the bootstrap modal is not visible

My goal is to trigger a modal window when a specific div is clicked using bootstrap modal. However, upon clicking the div, the screen darkens but the modal body fails to appear. Code: <html> <head> <title></title> ...

Tips for ensuring only one property is present in a Typescript interface

Consider the React component interface below: export interface MyInterface { name: string; isEasy?: boolean; isMedium?: boolean; isHard?: boolean; } This component must accept only one property from isEasy, isMedium, or isHard For example: <M ...

Why are double curly brackets used in the JSX syntax of React?

In the tutorial on react.js, a specific usage of double curly braces is highlighted: <span dangerouslySetInnerHTML={{ __html: rawMarkup }} /> Building on this, in the second tutorial titled "Thinking in react" found in React documentation: <sp ...

Issue with reverse document referencing in Mongoose

I've been searching extensively for a way to reference documents bidirectionally in Mongoose. Despite all the documentation and examples provided in Populate, they only show how to save the objectID of one document in another. Let's say I have a ...

Difficulty encountered when transferring an array from Xcode to JavaScript via SBJSON

In an attempt to transfer an array from Xcode to a local HTML file, I am utilizing jQuery in the HTML code. This involves using loadHTMLString: with baseURL to read both the HTML and included .js files. However, I am encountering an issue when trying to us ...

Error: Unable to locate module: Material-UI - Please check the path and try again

Encountering this error: Error message: Failed to compile ./node_modules/@material-ui/core/Modal/Modal.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'C:\Users\rifat\ ...

Utilizing AJAX for XML data parsing

I need help with formatting XML data into a table. The code I've written isn't working as expected. The XML data is structured in branches, causing it to not display correctly. Can someone assist me in fixing this issue? <!DOCTYPE html> &l ...

What steps should I take to display a Modal upon a successful Oauth2 redirect?

I am currently working on an older web application that utilizes the portal/portlet architecture. Within the application, I have a feature that loads in a modal when accessed. The modal includes navigation functionality that allows customers to navigate t ...

Identifying whether a Property in an Object is another Object

I'm planning to utilize JSON for stringifying the value of a property within an object, which will then be stored as a Tag on Google Calendar using Google Apps Script. The value in question is actually a double-nested Object (look at extraAttributes w ...

Tips for deactivating a single edit button

Is there a way to make it so that when I click on a checkbox, only that specific todo's edit button is disabled? Currently, clicking on a checkbox disables all edit buttons in the todo list. Any suggestions? class App extends Component { state ...

I am unable to log in using bcryptjs, but I have successfully been able to register a

Hey there! So I'm diving into Nodejs and I've managed to create a simple login/register API. For password encryption, I'm using bcryptjs. Testing it out on postman, I can successfully register a new user. However, when attempting to login wi ...

jQuery unable to locate elements or update class following AJAX response

My jQuery.on() event functions are working great when bound to specific elements like "a.my-link". However, I have one function that is bound to the document or body and then traverses multiple elements with the same class attribute. Certain lines in this ...

Tips for creating an effective dark mode toggle switch on a website

I was experimenting with creating a dark-mode switch for a website, but I'm not convinced that my implementation is the most efficient. Essentially, I ended up duplicating each file and adding a "2" at the end to create modified versions for each sect ...

Storing data as a JSON string in a JavaScript object and saving it to

Have you ever wondered why the cart object is saved as "cart" in the local storage instead of being an actual object? This discrepancy is causing the cart not to display correctly. This issue arose after deploying the website on Vercel. Storing "cart" as ...

How to Show a GIF in ASP.NET Core 3.0 When OnPost() is Invoked

I'm struggling to incorporate a GIF into my website, and after researching different sources, I've discovered that I need to utilize some Ajax and Javascript. However, I lack experience with both of these technologies. Is there anyone who could p ...

Is it possible to apply fog to a specific area in Three.js instead of being dependent on the distance from

Picture this: a vast THREE.PlaneGeometry representing the floor with a camera placed at an arbitrary spot within the scene. By manually adjusting the near and far values of the fog, I can effectively conceal the outer edges of the plane to create the illu ...

ExpressJS and cookies - Struggling to initialize a cookie with express-cookie

I recently followed a tutorial on YouTube (https://youtu.be/hNinO6-bDVM?t=2m33s) that demonstrated how to display a cookie in the developer tools Application tab by adding the following code snippet to the app.js file: var session = require('express- ...