The Three.js raycaster fails to intersect with objects once they have been displaced from their original position

I am encountering an issue with the raycaster:

When I place an object at the origin (0, 0, 0), the raycaster can detect it. However, if I move the object to a different position, like (0, 300, 0), the raycaster no longer hits the object.

I have double-checked that all directions are set up correctly. I even tried manually testing the raycasting on the moved object using Three.js functions and it was successful.

It appears that the raycaster.IntersectsObject(objects) is not applying the matrixWorld correctly to the Bounding Sphere.

Do you have any insights on why this might be happening?

I am aware of a similar post on this topic, but the solution mentioned didn't work for me:

Three JS - Strange raycast behaviour when objects are moved

The bounding sphere does have the correct values.

Answer №1

It is essential to ensure that the world matrix of your mesh is kept up to date. This can be easily rectified by invoking the mesh.updateMatrixWorld(); method.

var camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 400, 200, -300 );

var scene = new THREE.Scene();

var geometry = new THREE.SphereBufferGeometry(100, 100, 100);
var material = new THREE.MeshBasicMaterial({
  color: 0xaa5555
});

var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(0, 300, 0);
mesh.updateMatrixWorld(); // FIX
scene.add(mesh);

camera.lookAt( mesh.position );

var raycaster = new THREE.Raycaster();
var ray = raycaster.ray;
ray.origin.copy( camera.position );
ray.direction.subVectors( mesh.position, camera.position ).normalize();

var intersections = raycaster.intersectObjects(scene.children);
console.log( intersections ); 

var renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

renderer.render( scene, camera );
body {
  margin: 0;
}
canvas {
  display: block;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee9a869c8b8baedec0dfdfd7">[email protected]</a>/build/three.js"></script>

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

Set YouTube Playlist to start from a random index when embedded

I've been trying to figure out how to set my embedded playlist to start with a random video. Here's what I attempted: <iframe src="https://www.youtube.com/embed/videoseries?list=PLPmj00V6sF0s0k3Homcg1jkP0mLjddPgJ&index=<?php print(ran ...

Display images on a single dataset using Chart.js

How can I create a doughnut chart with 2 datasets where only one of them displays images? I managed to render both datasets and add images using chartjs-plugin-labels, but it applies the images to both datasets. Is there a way to specify which dataset shou ...

Problem with input field borders in Firefox when displayed within table cells

Demo When clicking on any cell in the table within the JSFiddle using Firefox, you may notice that the bottom and right borders are hidden. Is there a clever solution to overcome this issue? I have experimented with a few approaches but none of them work ...

Retrieve Browser Screen Width and Height using MVC3 Razor in the View

I am facing a challenge on my website where I need to generate a Bitmap dynamically and ensure it is rendered according to the width and height of the browser so that there are no overflow issues on the page. Although I have successfully created an image ...

When a class and ID are dynamically applied, the click event may not fire and the CSS may not be applied

Hey everyone, I am facing an issue with declaring id and class when creating a table dynamically. I have tried multiple functions to make my click event work but without success. Can anyone help me with this? Below is the code for my dynamic table where I ...

Enhance your user interface by adding a tooltip above a button

I am currently working on creating a button that can copy content from a variable into the clipboard using TypeScript and Material-UI. Here is what I have tried: const [copySuccess, setCopySuccess] = useState(''); const copyToClipBoard = async ( ...

Step-by-step guide on Setting up the bronto.sca.cart object using Bronto JSON

I have implemented the Bronto Tag Manager to track cart details successfully. After including the Bronto Commerce JavaScript snippet on my page, I am now able to create the bronto.sca object. While bronto.sca.config() and bronto.sca.id are returning valu ...

Directing to index.html using ExpressJS

JS, I am working on an express app that has various routes defined. However, I am facing an issue where if the router does not match any route, it displays index.html instead of redirecting to a specific route like '/*' as I expected. I am unsu ...

oj-select-one displays a comprehensive list of values in the dropdown

Typically, oj-select-one will only display the first 15 values before requiring the user to search for more. Is there a way to show all values in the dropdown list without needing to use the search function? I attempted to use minimumResultsForSearch as s ...

The autocomplete feature in Atom is not functioning as expected

Autocomplete+ is included with the installation of Atom and is activated by default. I have noticed that when I am coding, no suggestions are appearing. What could be causing this issue? Do I need to adjust any files in order for Autocomplete+ to functio ...

Creating DOM elements upon successful completion of an AJAX request with jQuery has never been easier. Here's a

I'm currently working on a project where I am dynamically creating a list of checkboxes using jQuery's $.ajax method. function load() { $.ajax({ type: "POST", url: "*************", data: "************ ...

"Every time an Ajax call is successful, the 'else' clause in

When it comes to using Ajax for user login in the system, I encountered an issue where the Ajax success function would always run the else statement even if the server returned a true Boolean value. This meant that even when the login credentials were vali ...

My goal is to programmatically eliminate captcha from a website

Is there a way to automatically remove capture from a Page using javascript (Greasemonkey)? The page's HTML structure seems complex, so any suggestions on how to achieve this would be greatly appreciated. <div class="wrapper"> <d ...

Obtaining the value of a specific dynamic `<td>` element using jQuery

My page layout resembles this design (I am unable to post an image due to insufficient points, so I have it hosted elsewhere) My goal is for jQuery to identify the specific email when a user clicks on the delete button. For instance, if a user clicks on & ...

How require works in Node.js

My current database connection module looks like this: var mongodb = require("mongodb"); var client = mongodb.MongoClient; client.connect('mongodb://host:port/dbname', { auto_reconnect: true }, function(err, db) { if (err) { ...

Simulation of loopback session

Currently, I am utilizing loopback in conjunction with express session to store cartId. However, for the purpose of making my tests function properly, it is essential that I inject cartId into the request session. Within my remote method, I have implemen ...

Remove duplicate elements from a JSON array

How can I add each item in an array for each duplicate? Transform: [ { "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60", "planning":[ { "uuid":"6D680178-9B05-4744-A004-163D4B3E1E84", "star ...

Sort through a list of objects using the criteria from a separate array

Looking to apply a filter on an array of objects: const myArray = [{ id: 4, filters: ["Norway", "Sweden"] }, { id: 2, filters :["Norway", "Sweden"] }, { id: 3, filters:["Denmark", "Sweden&q ...

Issue with Codeigniter's AJAX functionality causing div reloading to not function as intended

I am currently facing an issue where I can display text directly from the database on a webpage. However, when I edit the text in the database, I want it to automatically reload and show the updated text without having to refresh the entire page. Unfortun ...

guide on adding a variable to the link_to path

In my attempt to incorporate a variable into the link_to function below: <%= link_to '<button type = "button">Players</button>' .html_safe, live_players_path(:Team => @tmf) %> Whenever I click on this link, it seems to ...