The Raycaster in Three.js seems to be malfunctioning as the IntersectObjects method is providing intersection distances that are inconsistent and illogical

In my latest three.js project, I am developing a simple game where the user takes control of a spaceship named playerModel (a Mesh object with a basic BoxGeometry). The objective is to navigate through space while avoiding asteroids (SphereGeometry) that appear in the -Z direction and move towards the ship along the +Z axis.

One crucial function in this project is the detectCollisions function:

// This function checks for collisions between the playerModel and obstacles
function detectCollisions(obstacles) {
    var origin = playerModel.position.clone();

    for (var v = 0; v < playerModel.geometry.vertices.length; v++) {       
        var localVertex = playerModel.geometry.vertices[v].clone();
        var globalVertex = localVertex.applyMatrix4(playerModel.matrix);
        var directionVector = globalVertex.sub(playerModel.position);

        var ray = new THREE.Raycaster(origin, directionVector.clone().normalize());
        var intersections = ray.intersectObjects(obstacles);
        if (intersections.length > 0 && 
            intersections[0].distance < directionVector.length()) {
            console.log("Collision detected!");  
            return true;
          }
    }
    return false;
}  

During the game loop, I call this method by passing the array "spheres," which contains the asteroid objects:

function draw() {   
    // continuous drawing loop
    requestAnimationFrame(draw);
    // render THREE.JS scene
    renderer.render(scene, camera);

    if (!isGameOver) {
        generateSpheres();
        handleKey();  
        movePlayer(); 
        moveSpheres();
        if (detectCollisions(spheres))
            gameOver();
    }
}

The collision detection seems to be functional, however, visually it detects collisions even when the objects are far apart. The ray.intersectObjects method returns intersections with seemingly close distances, even though the actual positions of the objects are quite distant from each other. Additionally, there's a consistent issue with faceIndex being set at 37 for the intersecting asteroid object, which is puzzling considering the variations in radii and segments of the asteroids compared to the small size of playerModel. Any advice or insights would be greatly appreciated!

Answer №1

Perhaps the issue lies with the BoundingBox, especially if the Object's size changes without scaling.

Object.Model.geometry.computeBoundingBox();

However, I am not certain that this is the fix for your specific problem. Is it possible for you to share a jsfiddle link?

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

Can the load API in jQuery be utilized to load fragments using a class selector instead of an id?

I've been working on enhancing a website's dashboard by incorporating more widgets onto the page. Interestingly, these widgets are already present on another page within the same domain. After some research, I discovered that utilizing the load A ...

Tips for achieving proper styling and formatting of elements in jQuery UI

I've encountered an issue when trying to use jQuery UI after downloading it multiple times. In the examples provided with the download, the UI elements appear perfectly formatted, but when I implement them on my own pages, the styles and formatting ge ...

What is the best method to retrieve the minimum and maximum values of a range slider in PHP and

I've successfully implemented a custom range slider using the code snippet below: HTML: <input type="text" class="salary" id="salary" name="salary" style="border:0; color:#f6931f; font-weight:bold;&qu ...

Disregard the ng-blur event for specific elements

In my search feature, I have a suggestion box that appears below the search field when I start typing. I want the suggestion box to disappear when I click outside the search field, and also be able to click on a suggestion to perform a search. <input n ...

Unable to get knockout sorting to function properly

I have been working on organizing my grid and here is the code that I have so far: ko.moveInGrid = { // Creating a view model class for grid population viewModel : function(config) { this.data = config.data; this.currentPageIndex = ...

The argument for the e2e test is invalid because it must be a string value

Currently, I am conducting an end-to-end test for an Angular application using Protractor. However, I encountered an error while running the test for a specific feature file. The UI value that I am checking is - WORKSCOPES (2239) Below is the code snippe ...

Enhance Your Website with Bootstrap 4 Card Image Zoom

Is it possible to add an image zoom effect to Bootstrap 4 cards? I found some inspiration at . Below are the codes I have used: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha ...

Storing a JSON as a cookie in a Django response

Is there a way to store a dictionary/json object in a client-side cookie from Django and retrieve it as a JavaScript object? response = HttpResponseRedirect(reverse('app:home')) response.set_cookie('cookiekey', 'value') retu ...

Designing an architecture for a Java, Android, and database application - what will the final app's appearance be

I am currently working on a website where users need to complete tasks using an Android device: Fill out a simple HTML document. Sign the document on their Android device. Save the data entered into a database on the website. Some key points to consider ...

Dealing with nested file includes in PHP and passing values to a JavaScript function

When the button is clicked on login.php, it triggers the execution of redirect.php. This redirect.php file carries out Twitter authentication, which includes invoking another file that eventually calls index.php. index.php provides the result in the form ...

The operation of accessing a property of an undefined element fails due to unavailability, hence the error "Cannot

Hey everyone, I'm encountering an issue with opening a project developed in Angular 5.2.0 with Angular CLI version 1.7.4, while my Angular CLI version is 14.0.7... I ran "npm install" without any errors, but when I run "ng version" to check the local ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

Exploring Angular2's ability to interpret directive templates using the ng-container

Recently delving into angular2, I ventured into creating dynamic forms and generating fields by following the guide provided in this URL. The result was as expected. The dynamic form component renders each field one by one using ng-container, like shown b ...

How can I change an array to a string in JavaScript/jQuery and add a specific

Currently, I am tasked with the challenge of converting an array into objects. Furthermore, I also need to add something before each object is displayed. var arrayList = ["image1.jpg","image2.jpg","image3.jpg"]; The desired outcome should look like this ...

Error encountered while building with Next.js using TypeScript: SyntaxError - Unexpected token 'export' in data export

For access to the code, click here => https://codesandbox.io/s/sweet-mcclintock-dhczx?file=/pages/index.js The initial issue arises when attempting to use @iconify-icons/cryptocurrency with next.js and typescript (specifically in typescript). SyntaxErr ...

Navigational menu header leads to specific location on the page

I need the dropdown menu header to both open the related menu and display the content of the first element of the submenu, which is an anchor link on the page. Here is the HTML code for the Dropdown Menu: <div class="collapse navbar-collapse" id="myNa ...

Issue with Chrome not triggering onMouseEnter event when an element blocking the cursor disappears in React

Important Note: This issue seems to be specific to Chrome Currently, React does not trigger the onMouseEnter event when a blocking element disappears. This behavior is different from standard JavaScript events and even delegated events. Below is a simpli ...

Reinstall software using the information in the package-lock.json file

Imagine this situation: I added certain libraries like jquery and bootstrap using the command npm install. As a result, npm created a package-lock.json file which contains information about the installed packages. When I uploaded my project folder to a g ...

Attempting to display a grid of product listings using a Websocket connection and an Express server

Recently, I attempted to create a live table of products using websockets for real-time updates. While I am new to this concept, I decided to upgrade an old project with websockets. Unfortunately, my attempts were unsuccessful, which is why I am seeking he ...

How can I incorporate multiple states into a conditional statement in ReactJS?

Is there a more efficient way to achieve this task? I'm struggling to come up with a cleaner solution as the current approach looks messy. I need to check multiple states in an if statement and the only method I can think of right now is the one prese ...