Guide to Casting Rays from Any Given Location

I encountered an issue while working on a project using Three.js. In this project, users input x and y coordinates which results in a point being added to a Three.js scene. I need to calculate whether there is an object behind or in front of this point. I attempted to utilize the Raycaster feature, but struggled to find a straightforward example demonstrating how to use it with a vector defined by a point.

var projector = new THREE.Projector();
    var directionVector = new THREE.Vector3();
     /* How can I implement a vector specified by my initial point?

     var origin = new THREE.Vector3(x, y, 0 );

     Instead of using the camera vector as shown below?
     */
     projector.unprojectVector(directionVector, camera);
     directionVector.sub(camera.position);
     directionVector.normalize();
     var ray = new THREE.Raycaster();
     ray.set(camera.position, directionVector)
     var intersects = ray.intersectObjects(scene.children);
        if (intersects.length > 0) {
            console.log(intersects);
        }

Answer №1

If you need to cast rays from a specific point, follow this method:

var raycaster = new THREE.Raycaster(); // initialize once and reuse
var origin = new THREE.Vector3(); // reuse it
var direction = new THREE.Vector3(); // reuse it
...

origin.set( x, y, z );
direction.set( 0, 0, - 1 ).normalize(); // ensure the direction vector has unit length
raycaster.set( origin, direction );
var intersects = raycaster.intersectObjects( objects, recursiveFlag );
if ( intersects.length > 0 ) {      
    // your custom code        
}

This applies to three.js version r.75

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

When using Vue.js, pressing the enter key will automatically insert a <br> tag into the text output

I am in need of implementing basic text editor functionality into an application. I currently have a textarea where user input is reflected in a paragraph. I have implemented event listeners for spacebar and enter key presses within the textarea to trigg ...

Ways to showcase contents inside a specific div when hovering with a mouse

I am working with a div structure that includes menus and items within each menu. <div id="navigate"> <div class="menu"> <div class="group">Mail</div> <div class="item">Folders</div> <div clas ...

I am looking to implement a function in JavaScript that will prevent the next button from being enabled until all options

I have a total of 6 dropdown menus along with a next button and previous button. I want the next button to be disabled until all 6 dropdown menus are filled out. Once all 6 dropdown menus are filled, the "next" button should become enabled. Below is the c ...

Having difficulty removing whitespace from JavaScript code

Struggling to align a div using Javascript on my professor's website to match the spacing of the rest of the site. Despite attempts at adjusting margins and following suggestions from other Stackoverflow.com threads (e.g. CSS: Center block but left al ...

angular controllers and directives using scope

I'm just starting to learn angular and I've run into a problem with the scope in my directive and controller. Take a look at my code: Controller: var myApp = angular.module('myApp', []); myApp.controller('testCtrl', fun ...

Hold on until the page is reloaded: React

My current setup includes a React Component that contains a button. When this button is clicked, a sidePane is opened. What I want to achieve is refreshing the page first, waiting until it's completely refreshed, and then opening the sidepane. Below i ...

What is the process for sending JavaScript with an Ajax request?

Working with ajax and javascript for the first time, I'm no expert in web development. Here is the code I've written and tested so far. I have a select div containing some options. <select id="month" onchange="refreshGraph()"> When an op ...

Retrieving modified object values in Node.js - A comprehensive guide

How can I retrieve the modified value of an object? The file index.js is executed before index2.js and here's what my code looks like: var object = { size:'5' }; var setSize = function(size) { object.size = size; } exports.object ...

``Intriguing shadow anomalies in Three.js on planes that intersect

I am facing an issue with shadow artifacts appearing on my 3D model of a furniture module. These artifacts show up at the intersection points of two planes, where shadows should not be present. Here is a screenshot showcasing the shadow artifacts Despite ...

Adjust the month to be plotted on the X-axis of the ColumnChart using the specified

My ORIGINAL POST: I've put together a fiddle to showcase how my data is sourced from JSON and displayed in a ColumnChart. https://jsfiddle.net/w4dokdt9/3/ This is an example of how my JSON data is structured: [{"lPlusScoreID":1,"jan":60.03,"feb":4 ...

The Jquery test isn't functioning as expected - the green square fails to display

So, the concept is that the green square should appear when your mouse hovers over the red square, but it's not working as expected. Here's the code snippet: <html> <head> <script type="text/javascript" src="jquery-1. ...

The push method is not pushing the elements

Why aren't the values being pushed into the array in the code snippet below? app.get("/overview", (req,res)=>{ const email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="600a01030b4e10120f4e0f06060 ...

Javascript - Displaying data retrieved from an external API with JSON

Seeking advice on how to effectively attach JSON values obtained from xhr.response to HTML labels. Any suggestions are appreciated. Thank you. On a different note, does anyone have recommendations for websites that provide concise explanations of basic JS ...

utilizing a spacemouse in conjunction with autodesk forge

Recently, I acquired a 3dconnexion spacemouse and have been attempting to configure it to work with the forge viewer. Fortunately, I came across some JS samples in the SDK for three.js that worked flawlessly. It seems both forge and three.js utilize webgl ...

Navigating through React Native - A guide to accessing the initial navigation state on React Navigation

Is it possible to retrieve the initial state in a similar format as what is provided by the onStateChange prop in NavigationContainer? Unfortunately, onStateChange does not run during the initial render. While I was successful in obtaining the state whil ...

The data from the Vue.js instance is not available when accessing the Vuex store

My current task involves utilizing an API call to a django-rest backend in order to populate my data-store. The API call is functioning properly. Upon loading index.html, I am able to inspect both store_.state.products and v.$store.state.products, which s ...

How to Generate a JSON Cookie Array?

Currently, I am in the process of leveraging jquery's json to form a cookie array. The script I have managed to put together thus far is functional except for the part pertaining to the array. Would someone be able to guide me on how to construct an a ...

A guide to creating a JavaScript function that outputs a script in string form

Currently, I am utilizing angular and seeking to add a script to my directive's template. My goal is to create a function that can take the necessary parameters for the script and return it as a string. This approach would prevent me from having to em ...

Executing a pair of queries within the same table and integrating them within a unified route

How can I efficiently execute two queries on the same table in my project? I have been considering using promises, but my knowledge on them is limited. Even though I've researched about it, I am struggling to implement the correct structure. My main ...

Altering the values of nested object properties

Currently, I am struggling to update the values of keys within an array of objects. The JSON structure of the object I'm working with is quite intricate, with each object in the array potentially containing a different number of keys. Here is a simpli ...