Encountering an unusual issue while implementing collision detection with THREE.Raycaster in version r68

Up until now, I've successfully utilized the THREE.Raycaster in my game engine for testing collisions across various elements. It has been reliable and effective.

However, a puzzling issue has recently arisen that has left me stumped. Despite believing that my logic and code are correct, the expected outcomes are not aligning as they should. This discrepancy has prompted me to seek assistance, as there may be something obvious that I am overlooking.

The current scenario involves casting rays from the central point at the top of a group of meshes, individually in a circular arc. These meshes all belong to a parent Object3D, with the objective being to assess collisions between the main mesh and other child meshes of the parent element. To visualize these rays, I am employing the THREE.ArrowHelper.

An image illustrating the output of my code can be viewed here - https://i.sstatic.net/DjW0f.jpg

While the positioning of the ArrowHelper objects appears accurate (origin:direction), there is an underlying issue with this depiction generated by the following code:

var degree = Math.PI / 16,
    tiles = this.tilesContainer.children,
    tilesNum = tiles.length,
    raycaster = new THREE.Raycaster(),
    rayDirections, rayDirectionsNum, rayOrigin, rayDirection, collisions,
    tile, i, j, k;

for (i = 0; i < tilesNum; i++) {
    tile = tiles[i];
    rayOrigin = new THREE.Vector3(
        tile.position.x,
        tile.geometry.boundingBox.max.y,
        tile.position.z
    );
    rayDirections = [];

    for (j = 0; j < Math.PI * 2; j += degree) {
        rayDirections.push(new THREE.Vector3(Math.sin(j), 0, Math.cos(j)).normalize());
    }

    rayDirectionsNum = rayDirections.length;

    for (k = 0; k < rayDirectionsNum; k++) {
        rayDirection = rayDirections[k];

        raycaster.set(rayOrigin, rayDirection);

        collisions = raycaster.intersectObjects(tiles);

        this.testRay(rayOrigin, rayDirection, collisions);
    }
}

The testRay function is structured as follows:

testRay: function (origin, direction, collisions) {
    var arrowHelper = new THREE.ArrowHelper(
        direction,
        origin,
        1,
        (collisions.length === 0) ? 0xFF0000 : 0x0000FF
    );

    this.scene.add(arrowHelper);
}

Evidently, the rendering depicts some inconsistencies. Rays that intersect with other meshes should display in blue, while those without collision should appear red. The current image reveals significant discrepancies, with multiple blue intersections on certain rays and inconsistent results in general.

This situation presents a perplexing challenge - why are numerous expected blue collisions manifesting as red? How are rays from edge tiles registering blue collisions with non-existent elements?

This conundrum has me scratching my head (figuratively and literally), and any insights or assistance would be immensely appreciated!

Answer №1

The solution didn't lie within the code provided but rather outside of it, and I don't believe it was related to the outdated r68 build.

When creating the tile meshes, I discovered that I needed to set three properties on them

tileMesh.matrixAutoUpdate = false;
tileMesh.updateMatrix();
tileMesh.updateMatrixWorld(); // this is new

I had been doing the first two steps, but neglecting the last one. Although I'm not sure why this step is necessary, implementing it resolved my issue. In my scene, there was an AxisHelper, and upon closer inspection of the original image, I noticed that all the ArrowHelper objects pointing blue were actually directed towards the AxisHelper. This struck me as peculiar since the AxisHelper was part of the scene itself, not the tilesContainer. Placing the ArrowHelper objects in the tilesContainer did not make a difference.

During the rendering process, the raycaster code was executed before the AxisHelper was added to the scene and prior to the initial render taking place. The issue could also be temporarily resolved by running the raycaster code after adding the AxisHelper, although this was more of a quick fix than a proper solution.

Hence, the ultimate fix was to include .updateMatrixWorld() for the tiles. As a result, the output now appears like this https://i.sstatic.net/1HfA0.jpg, which is accurate (the length of the ArrowHelper objects have been adjusted to prevent overlapping).

A special thanks to Manthrax for his valuable assistance with this matter.

Answer №2

Perhaps there could be a confusion between local and global space in your code. It's not immediately clear where the issue lies, but it seems like all your position and direction calculations are based on the local system of the tilesContainer. Have you ensured consistency in handling local vs global coordinate systems?

For instance, adding your arrowHelper to the scene instead of the tilesContainer might be causing unexpected results. If the tilesContainer has a rotation set, the arrows may point in a different direction than intended.

Have you considered adding the arrows to the tilesContainer to see if that resolves the issue?

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

Cannot use Axios instance in Next.js due to error stating 'Localstorage is not defined'

I am currently working on a React app and have created an Axios component that I would like to reuse: import axios from 'axios' import dynamic from 'next/dynamic' const baseUrl = 'http://127.0.0.1:8000/' const axiosInstan ...

"Implementing automated default values for Select/dropdown lists in ReactJs, with the added capability to manually revert back to the default selection

After browsing multiple websites, I couldn't find a clear solution on how to both set and select a default value in a select element. Most resources only explain how to set the value, without addressing how to reselect the default value. My Requireme ...

What is the best way to invoke my Python function within my JavaScript file?

I am facing an issue with using my Python function in JavaScript. Although the actual code I am working on is more complex, I have simplified it to demonstrate the problem below: main.mjs dbutils.notebook.run("./aPythonFile.py", 5, {"parame ...

How can we ensure that paragraphs are validated correctly in a multiline Textbox using JavaScript?

Currently, I am attempting to validate text (paragraphs) in JavaScript for a multiline textbox. The requirement is that after entering text into the textbox, the very first letter should be changed to a capital letter while the rest should remain in lowerc ...

Issues with functionality of Bootstrap 5 popover in responsive JavaScript DataTable

As I work on constructing a web page for my hobby, I am utilizing Bootstrap 5.3.3 and JS DataTables 2.0.5. Within the page, there is a table displaying data about various players. I have implemented a feature where clicking on certain cells triggers a popo ...

The column headers are not being shown in Jquery datatables

This particular question is related to the thread found here. Nevertheless, my situation differs slightly. I am looking to implement the same datatables example from the aforementioned question, which can be accessed here. In that example, you must provide ...

What is the best way to pause the previous timer and display only the upcoming timer in a React application?

When comparing the scheduled times with the current date-time, I noticed that the values for upcoming schedule times are displayed correctly. However, when the time has already passed, it shows negative values. Instead of this, I would like to display &apo ...

The issue arises when trying to bind a component with a child state using ui-router

Just starting out with angular/uiRouter and I have a question. I would appreciate any guidance from those with more experience on how to bind a component with a state whose parent is abstract. Here is what I have implemented so far: States { ...

Cross-site communication with Ajax using both POST and GET requests

As a beginner in JavaScript, I'm facing challenges with implementing ajax POST and GET requests. While I can successfully do it using Google Postman as shown here https://i.sstatic.net/Cegxj.pnghttps://i.sstatic.net/ovJT0.png, the problem arises when ...

Learning about the functions Promise.all and Array.map()

My current project involves retrieving data from multiple APIs and aggregating them into a final array that will be displayed in the UI using React. Let me explain the scenario. First, I retrieve the main data from the primary API: const response = await ...

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 ...

Managing Subdomains in Nuxt.js Using Vue.js

I am currently developing a Nuxt.js (vue.js) application. I am aware that Nuxt automatically generates routes based on the directory structure within the 'pages' folder. I am curious about how it would handle subdomains. My goal is to establish ...

What is the best way to implement post-processing effects using EffectComposer render passes without erasing previous render passes?

I've got a cool setup in three.js with a red plane in the background and a rotating white cube in the foreground. However, I'm running into an issue when I try to add a TAARenderPass to the cube - it keeps making the red plane disappear along wit ...

Issue encountered: "An error has occurred stating that your cache folder contains files owned by root. This is likely a result of a bug present in older versions of npm. This issue arose during the execution of the

While attempting to create a new react app using the command npx create-react-app example_app, I encountered the following issue: [ Your cache folder contains root-owned files, due to a bug in previous versions of npm which has since been addressed sudo ...

Tips for incorporating CRUD functionality using jQUery

Recently, I successfully created a users list using CRUD with PHP, MySQL, and Bootstrap. Everything was working smoothly. However, I faced some errors when trying to integrate jQuery to avoid page refreshes during operations. Creating/inserting new users ...

AngularJS causing a modal popup to appear even when the associated button is disabled

When using a Bootstrap modal popup form that opens on button click in AngularJS, I noticed that the modal still appears even when the button is disabled. Can someone help me understand why this happens? Here is the code for the button: <a class="btn b ...

Is there a library available for generating QR codes on the server side and saving them directly to a database

My Goal: I am looking to create a functionality where, upon clicking "Generate QRCode," JavaScript will utilize the local machine's datetime to generate an md5 hash in the MMDDYYHHMMSS format. I then want this hash to be sent to the server to produce ...

What is the best way to pass a module from the controller to a Jade/Pug template and then use it as an argument in an event handler within the template?

I passed the module 'naija' to a template from the controller in this way: res.render('testing', {title:"filter setting page", nigeria:naija }); The func ...

Disable or eliminate the event listener

Working on my Angular2 application, I've set up an RxJS timer that sends notifications to users when they are logged in. The twist is, the notification should only be sent if the tab is active; otherwise, the scheduler should pause or stop. I have man ...

Is it possible to reference and assign controllers from templates in Angular 2 like in previous versions?

In my opinion, one of the great things about Angular 1 is that developers can write business logic in controllers without having to reference anything related to markup or rendering. After reading the Angular 2 documentation, I came across this code snipp ...