The THREE.Raycaster is detecting intersections with the mesh's initial position following the position.set() method

When using Three.js, I encountered an issue where the THREE.Raycaster does not recognize an object's new position set using position.set(). If the object is left at the default position of 0,0,0, the mesh is properly intersected.

function initialize(){
var targets = [];
var object;
// Additional scene initialization code...

// Creating a cube object and positioning it at (-10,0,-10)
    var objectGeometry = new THREE.CubeGeometry(2,2,2);
    var objectMaterial = new THREE.PhongMeshMaterial({color: 0xEEEEEE });
    object = new THREE.Mesh(objectGeometry, objectMaterial);
    object.position.set(-10, 0, -10);
    scene.add(object);
    targets.push(object);

// More objects are created and added to the scene

}

I have a character controller that can be moved around with a camera following it. To test, I connect the character (obj) and the targets in a function called testRay();

function testRay(obj,targets,distance){
// Code to ensure the ray is always pointing out in front of the character
    var endRayX = (Math.cos((270*(Math.PI/180))-obj.rotation.y)*distance + obj.position.x);
    var endRayZ = (Math.sin((270*(Math.PI/180))-obj.rotation.y)*distance + obj.position.z);
    var vector = new THREE.Vector3(endRayX,obj.position.y,endRayZ);
    var raycaster = new THREE.Raycaster(obj.positon,vector);
    intersects = raycaster.intersectObjects(targets);
    if(intersects.length>0){
        console.log("intersects.length: "+ intersects.length);
        console.log("intersects.distance: "+ intersects[0].distance);
        console.log("intersects.face: "+ intersects[0].face);
        console.log("intersects.point: " + intersects[0].point);
        console.log("intersects.object: " + intersects[0].object);
    }
}

During each requestAnimationFrame(main) call, I call testRay() with the character controller and targets to check for intersections.

function main(){
    // Some other code
    testRay(character,targets,30)
    window.requestAnimationFrame(main);
}

The issue lies in getting the ray to intersect the object at its new position set with position.set() during creation. I observed that simply intersecting the objects can move them around, which also shifts the intersection coordinates. Should I move the object after adding it to the scene? Does it make a difference?

Answer №1

Although this question may be from some time ago, it could still provide valuable insight for someone in need: I encountered a similar issue recently. It appears that three.js relies on the object's world transform matrix for ray intersection. Depending on the sequence of operations, this matrix may not have been properly updated after the position.set(); and before the raycaster.intersectObject(); function is called. Typically, three.js handles this automatically when rendering objects in the scene, but in my scenario, the object was not actually present in the scene. To resolve this, I simply had to invoke object.updateMatrixWorld() before performing the raycasting.

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

Building 3D models using react-three-fiber

react-three-fiber offers a convenient method called useLoader for loading models. The examples demonstrate how to load models from a specified path or URL. I have stored the binary representation of my model in the IndexDB within the browser. To showcase ...

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

Creating a Custom Select Option Component with Ant Design Library

Is it possible to customize options in an antd select component? I have been trying to render checkboxes alongside each option, but I am only seeing the default options. Below are my 'CustomSelect' and 'CustomOption' components: // Cu ...

A customizable and adaptable Tetris-inspired CSS design perfect for any screen size

If we imagine having a block like this: <div class="block"></div> There are different sizes of the block: <div class="block b1x1"></div> <div class="block b2x1"></div> <div class="block b1x2"></div> For i ...

Drop-down options disappear upon refreshing the page

Code snippet for sending value to server using AJAX in JavaScript In my script, the status value may vary for each vulnerable name. When selecting a status option and storing it in the database through AJAX, the selected value is lost after refreshing th ...

How can I incorporate a feature in my Angular application that allows users to switch between different view types, such as days, using JavaScript

Greetings, community! I am currently utilizing version 5 of the fullcalendar library from https://fullcalendar.io/ in my Angular 9 application. I have noticed that the calendar offers various options to change the view type as shown below: https://i.stac ...

Adjusting the text of a button when hovering over it will also trigger a resizing of the

Currently, I am facing an issue where the bootstrap button's size changes when hovered over. My intention is to have the bootstrap button remain a fixed size while only the text inside it changes using javascript for mouseover and mouseout events. How ...

Develop an array of unique objects with multiple dimensions, ensuring no duplicates are included

Seeking assistance for the following task: I am trying to create a new multidimensional array of objects based on an existing array of objects: [ {number:111, connectedNumber: 112, ...}, {number:112, connectedNumber: 111, ...}, {number:113, connectedNumbe ...

Flipping the camera rotation matrix in three.js

I am struggling with a scenario involving objects and a camera being controlled by a trackball. Whenever I add a new object to the main object, I want it to maintain its original orientation regardless of how the camera has moved around. For instance, with ...

Utilizing the ng-if directive to choose the second element within an iteration of an ng-repeat loop

I am currently working on a project where I need to organize and group content by day. While the grouping function is working fine, I am facing an issue with treating the first two items in the loop differently from the rest. I have experimented with using ...

Tips for retrieving information from a highstock chart

Imagine I have a sample highstock chart on my website, similar to the one at this link. Is there a way to extract the data from the chart itself, even if the data used for creating the chart is not accessible to others? <img src="http://www.highchart ...

Troubleshooting Problems with Ajax across Different Web Browsers

I am facing an issue with my ajax function - it works perfectly on Chrome and Firefox, but not on Internet Explorer 8. Can anyone help me identify the problem? Here is the HTML section: <select id='choices'> <option id="no" value="no" ...

Combine Vue Plugin Styles without Using Components

Question Time To clarify, when I mention 'without component', I am referring to my plugin being a custom Vue Directive that does not rely on a template. It acts as a wrapper for a class, without the need for an additional component. However, I a ...

Adjust the constant state in one component using another component

I created a React application with a simple menu that switches state when clicked to open and close it. The functionality works as expected with the menu button located within the same component. However, I now face a challenge in trying to open the menu f ...

How can I extract just the initial 2 letters of a country name using AmCharts maps?

Having trouble with Amcharts maps. I have a map that displays countries as United States, but I only want them to show as US. Is there a country formatter available for this issue? Any help is appreciated. ...

My toggleclass function seems to be malfunctioning

I am encountering a strange issue with my jQuery script. It seems to work initially when I toggle between classes, but then requires an extra click every time I want to repeat the process. The classes switch as expected at first, but subsequent toggles req ...

Embed the parent component within the child component

I have two files called Recursive.vue and Value.vue. Initially, when Recursive is the parent component, mounting Recursive within itself works perfectly. Similarly, mounting Value within Recursive and then Value within itself also works fine. However, an ...

Stop users from saving the page in Next.js

I'm currently working on a NextJs project that involves building an editor application. I want to ensure that the editor functionality does not work when users attempt to save the page in a different format, similar to how applications like Youtube an ...

One requirement for a directive template is that it must contain only a single root element, especially when using the restrict option to E

I am currently managing an older AngularJS application (v1.3.8). Why is the demo application showing me this error? The directive 'handleTable' template must have only one root element. sandbox.html <!DOCTYPE html> <html> <he ...

Executing an Ajax request. Best method for transmitting various data elements:

I am currently attempting to perform an ajax call with multiple data inputs. When I send only one string of data, I use the following method: $.ajax({ url: "php/update_lastordning.php", type: "POST", data: "elId=" + elId }); To retrieve t ...