The Raycaster.intersectObjects function in Three.js is only able to detect intersections with the front surface

My current project involves generating a world filled with blocks on the ground upon mouse click (using mouse click coordinates that I've calculated). To ensure that each new block doesn't intersect with existing ones, I implemented a check using THREE.Raycaster. Essentially, I cast rays from the center of the block in all directions towards its vertices.

var ln = preview.geometry.vertices.length;

//for each vertices we throw a ray
for(var i = 0; i < ln; i++){
    var pr_vertex = preview.geometry.vertices[i].clone();
    var gl_vertex = pr_vertex.applyMatrix4(preview.matrix);
    var dr_vector = gl_vertex.sub(preview.position);

    var ray = new THREE.Raycaster(preview.position, dr_vector.clone().normalize());
    var intersects = ray.intersectObjects(objmanager.getAllObject(), true);

    //if there is intersection
    if(intersects.length > 0 && intersects[0].distance < dr_vector.length()){
        //hide preview material
        preview.material.opacity = 0;
        //exit checking
        break;
    }
}

The object being referred to as "preview" is crucial for this functionality and the code works flawlessly. However, I encountered an issue with Raycaster.intersectObjects only detecting intersections with the front face of the tested object. When the ray started from inside the object, it failed to recognize collisions with the surface. This led me to believe that intersectObjects only functions with the front surface of objects. Is this assumption correct?

In an attempt to address this limitation, I explored using THREE.DoubleSide to create double-sided objects. Unfortunately, this resulted in a shader initialization error:

Could not initialise shader
VALIDATE_STATUS: false, gl error [0] three.js:25254
    buildProgram three.js:25254
    initMaterial three.js:23760
    setProgram three.js:23830
    renderBuffer three.js:22371
    renderObjects three.js:23061
    render three.js:22935
    animLoop

I am currently utilizing THREE.MeshLambertMaterial but switching to MeshBasicMaterial rendered Raycaster.intersectObjects ineffective altogether.

This roadblock has left me seeking solutions. If anyone has any ideas on how to address this issue, I would be immensely grateful. Otherwise, I might have to resort to manually testing collisions against individual faces of objects, which could significantly impact performance.

Thank you in advance.

===============

Edit: It's worth noting that I'm working with the latest version of three.js, estimated to be around r63.

Answer №1

In order to achieve hits on both surfaces, the following needs to be configured:

object.material.side = THREE.DoubleSided

This setting will ensure detection on both sides.

Answer №2

When using a double-sided material, keep in mind that you will encounter two intersections :

surface.properties.material.side = THREE.DoubleSide

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

Did the overload resolution encounter an error?

https://i.sstatic.net/tTrmS.png I'm currently attempting to display a TTF Font Loader on a Plane using Promises, converting it to a Texture, and then mapping it on a MeshBasicMaterial in index.js. However, I keep encountering the error mentioned abov ...

Obtain identical encryption results with CryptoJS (JavaScript) and OpenSSL (PHP)

I am in the process of integrating a PHP encryption function into a ReactJS application. I have a requirement to transmit the token in a specific format that was generated using the OpenSSL library function (openssl_encrypt). It has been observed that the ...

Leverage the power of the React useFetch hook with an onclick/event

My component utilizes a custom reusable hook for making HTTP calls. Here is how I am using it: const { data, error, isLoading, executeFetch } = useHttp<IArticle[]>('news', []); Additionally, within the same component, there is a toggle che ...

Unable to successfully delete all channels in discord.js

I'm currently working on a bot designed to delete all channels within a Discord server. Here is the code I have written: const { Client, GatewayIntentBits } = require("discord.js"); const client = new Client({ intents: [ GatewayIntent ...

Is it possible to drag the parent element but only select the text within the child

How can I make the parent div draggable, yet keep the text in the child span selectable? <aside draggable="true" id="dragme"> This is an aside, drag me. <span id="copyme" draggable="false">But copy me!</span> </aside> A simila ...

implementing an event listener for clicking on a 3D cube in Three.js

I have a unique situation in my code where I am working with two cubes and trying to add a click event listener to them. My goal is to alert the user on which cube they clicked. Surprisingly, adding the click event listener to the document worked perfect ...

Struggling to toggle the visibility of a table with a button - successfully hiding it, but unable to make it reappear?

I need a button that can toggle (show/hide) a table. Currently, my code hides the table successfully, but it fails to show the table again when I click the button. It seems like there is an issue with refreshing or redirecting after clicking the button for ...

Every time I try to create a new React app, I consistently run into the same error

I keep encountering this error every time I try to create a React app using create-react-app. ...

How can I load a URL without causing a page refresh?

While searching around, I stumbled upon this HTML 5 code snippet: window.history.pushState("object or string", "Title", "/new-url"); I started thinking: how can this be implemented? Is there a way to utilize this code to change the URL to without needin ...

What is the correct way to utilize preloads and window.api calls in Electron?

I am struggling with implementing a render.js file to handle "api" calls from the JavaScript of the rendered HTML page. The new BrowserWindow function in main.js includes: webPreferences: { nodeIntegration: false, // default value after Electr ...

What is the best way to handle and fix incorrect characters?

I have a JavaScript code snippet that is designed to check for invalid characters in a string. The only allowed characters are a-z, A-Z, 0-9, and -: var str = 'Some string!', invalid_characters = []; if (/^[a-zA-Z0-9-]*$/.test(str) == false ...

Prevent the function from running more than once

I need a specific function function toDiv() { $(".wrap"))) $('.barfill').each(function(){ var width=$(this).data('width'); $(this).animate({ width: width }, 500); var $perctext = $('<div>', ...

Angular deletes any leading whitespace during the rendering process

While working on a project, I encountered an issue with my Angular component. It's supposed to display a string from its input on the HTML page, but I noticed that leading whitespace is being stripped out. <span>{{value}}</span> The value ...

Converting a Jquery object into a Javascript object

Can someone help me decipher this piece of code? //... obj.dd.on('click', function(event){ $(this).toggleClass('active'); return false; }); //... $(function() { var dd = new DropDown( $('#dd') ); $(doc ...

The function os.platform in React and Electron mistakenly identifies the browser as the operating system instead of the actual OS

In my quest to locate the appdata folder for the application, I encountered a challenge where each operating system has a different path for the appdata or application support folder. To address this, I attempted to identify the OS type in order to deter ...

Send a PHP array to JavaScript to display a horizontal pop-up submenu on hover

Currently, I am engaged in the process of updating an old website. I have made modifications to the html, php, and switched from a MySQL database to an SQL database. All seems to be going well in these areas. My expertise lies in databases, PHP, SQL, and I ...

Angular.js reports that the custom HTTP response header is missing

Despite Chrome showing the correct POST response headers, my custom HTTP header X-Auth-Token is returning null in the callback function for the POST request. Angular.js seems to only be returning Cache-Control and Content-Type, with everything else showing ...

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...

JSON has difficulty retaining the value of the variable

I've been working on a piece of code that scans through a directory, extracts each file's name and content. The aim is to retrieve the data from these files, usually consisting of numbers or short pieces of text. var config = {}; config.liveProc ...

Navigating the intricacies of retrieving network errors within an AngularJS application requires a deep

I've encountered the following code snippet in abcd.js: $http({url: 'some url' , method: 'POST', data: , headers: {} }).then(function(response)) { ............. }, function error(response) { .............. }) When an error occurs ...