Raycasting for collision detection is not very precise

I am facing a challenge in my project where I have multiple irregular shapes like triangles, trapezoids, and other custom designs in a 2D scene all located on the Y=0 axis. I am currently working on writing code for collision detection between these shapes.

Since the shapes are complex and not just simple circles or rectangles, I decided to implement raycasting for collision detection.

var raycastCollision = function () {

        var originPoint = activeElement.position.clone();
        var vertices = activeElement.geometry.vertices;

        // Loop through each vertex
        for (var vertexIndex = 0; vertexIndex < vertices.length; vertexIndex++) {

            var localVertex = vertices[vertexIndex].clone();
            var globalVertex = localVertex.applyMatrix4(activeElement.matrix);
            var directionVector = globalVertex.sub(activeElement.position);

            var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize(), true);
            ray.ray.direction.y = 0;
            var collisionResults = ray.intersectObjects(elements);
            debug["ray" + vertexIndex] = ray;
            if (collisionResults.length > 0 && collisionResults[0].object != activeElement && collisionResults[0].distance < directionVector.length()) {

                debug["raycast detection"] = "HIT";
                break;
            }
        }
    }

ActiveElement represents the currently selected shape, while elements contains a list of all shapes in the scene.

The issue I am encountering is that the collision detection only works in certain scenarios, and I am struggling to identify the specific conditions causing this behavior. However, one thing is clear - it frequently fails to detect collisions when it should.

Can anyone help me pinpoint the error(s) in my code?

Edit: Here are examples of situations where the collision detection does not work properly and where it does: https://i.stack.imgur.com/YBNEM.png

https://i.stack.imgur.com/37X8P.png

Answer №1

Since my previous answer was incorrect, I have deleted it.

After testing your function on a sample scene, I found a solution that works well:

Visit this link for the solution

In your case, the issue seems to be related to parallel faces.

Below is a modified version that works for spheres:

var detectCollision = function () {

  var originPoint = spheres[0].position.clone();
  var vertices = spheres[0].geometry.vertices;

  //loop through all vertices
  for (var vertexIndex = 0; vertexIndex < vertices.length; vertexIndex++) {

    var localVertex = vertices[vertexIndex]; 
    var globalVertex = localVertex.applyMatrix4(spheres[0].matrix);
    var directionVector = globalVertex.sub(originPoint);

    var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize(),true);
    var collisionResults = ray.intersectObjects(spheres);

    collisionResults = collisionResults.filter(function(element)
    {
      return element.distance < directionVector.length();                                         
    });

    if (collisionResults.length > 0 ) {
        console.log('HIT: '+collisionResults);
        break;
    }
  }
}

}

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

Creating a Validation Form using either PHP or JavaScript

I need to create a form with the following columns: fullname, email, mobile, and address. If the visitor fills out the mobile field, they should only be allowed to enter numbers. And if the visitor fills out the email field, they should only be allowed to ...

Obtaining form data from connected drop-down menus and sending it to PHP

My webpage contains a form with 2 dependent drop-down lists. When a user selects a value from the first list, it populates the second list for the user to make another selection. However, when I try to submit the form data to a PHP page to insert into a M ...

When attempting to send a request for the JSON body to Node.js using the await fetch method, I encountered an issue

Recently, I started working with node js and attempted to fetch JSON data using the code below: const req = await fetch( "http://localhost:3000/api/auth/signin", { method: "POST", header:{ 'Accept':&apo ...

The object THREE.DRACOLoader does not have a constructible function

When importing the three js and draco modules as shown below: import * as THREE from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e7938f958282a7d7c9d6d5d6c9d6">[email protected]</ ...

Best practices for including jQuery in ASP.NET (or any other external JavaScript libraries)

Can you explain the distinctions among these three code samples below? Is there a preferred method over the others, and if so, why? 1.Page.ClientScript.RegisterClientScriptInclude(typeof(demo), "jQuery", Re ...

Unable to Retrieve JSON Output

PHP Code: $contents = ''; $dataarray = file('/location/'.$_GET['playlist'].''); //Loading file data into array $finallist = ''; //Extract Track Info foreach ($dataarray as $line_num => $line) //Loopin ...

Failure to trigger a follow-up function in webSQL transaction's success callback

Review the code below. I have called setQuestion() within the successCallBack of db.transaction but am encountering an error: Uncaught TypeError: this.setQuestions is not a function. Can you spot any issues in my code? game.module( "game.scenes.scene" ) ...

Explore a variety of images within an array using Gatsby and Markdown documents

After spending more than 6 hours on this, I've decided to call it quits for today. However, I'm hoping someone out there might have a solution. The problem at hand is as follows: I'm trying to include an array of images in a Markdown file t ...

When utilizing Ionic with Angular, it is difficult to access the hardware back button on mobile devices that have buttons located within the display/screen

When trying to access the hardware back button in my app, I encountered an issue where I couldn't produce an alert message to the user before the app closed. After posting a question on Stack Overflow (link of the question) and receiving help from the ...

yet another scenario where the component's state changes without the component reflecting those changes

My react component includes a state variable called: showEditor When showEditor is set to false, the component should display a div containing a number (initially showEditor is false). If the state variable is true, the component should display a textbox ...

The Mongoose connection keeps failing to reconnect and maintain a stable heartbeat

I am facing an issue with the automatic reconnection feature in mongoose on my project. Despite configuring it to reconnect after a certain interval, it does not work as expected. Even if the credentials are correct, mongoose should attempt to log in perio ...

Javascript: recursive function fails to return existing value

I'm attempting to recursively loop through an array in search of a key that matches a specified regex pattern. Once the condition is met, the loop should halt and return the value of the key. The issue I am facing is that although the loop stops corr ...

Is the unit test for attribute failure specific to running it on only one node?

I am currently using Enzyme and Jest to verify the presence of an id attribute in a dropdown list. import React from "react"; import { mount } from "enzyme"; import ListPicker from './ListPicker.js' describe("ListPicker", () => { let props ...

Utilizing HTML and JavaScript to Download Images from a Web Browser

I'm interested in adding a feature that allows users to save an image (svg) from a webpage onto their local machine, but I'm not sure how to go about doing this. I know it can be done with canvas, but I'm unsure about regular images. Here i ...

Convert angular-tree-component JSON into a suitable format and dynamically generate checkboxes or radio buttons

Currently, I am using the angular-tree-component for my treeview implementation. You can find more details about it in this reference link. The array structure I am working with is as follows: nodes = [ { id: 1, name: 'root1', ...

AngularJS enhances user experience by allowing textareas to expand upon click

I am just starting to learn about angular.js and I'm wondering how to add a text area when clicking on an image. ....... ..... ..... </thead> <tbody> <tr ng-repeat="stu in Studentlist"> <td>{{stu.rollno}}</td> <td> ...

Parsley JS failing to validate

I attempted to validate my form using parsley.js, following the instructions from the official documentation. However, for unknown reasons, it is not functioning as expected. Below is the code snippet: <div class="container"> <div class= ...

Encountering a 404 Error on all routes except the home page when working with the Express Application Generator

While working on developing a day planner, I encountered an issue with the routes. I am consistently receiving a 404 error for any route other than the main Home page route (index or "/"). Below is the content of the app.js file: var express = require(&ap ...

Transform the character encoding from a non-standard format to UTF-8

Imagine a scenario where there is a page with <meta charset="EUC-KR">, let's call it address-search.foo.com, that allows users to search for an address and sends the data to a specified URL by submitting an HTML form using the POST met ...

Discovering the status of a wrapped component using Jest

const wrapper = mount( <ContextProvider> <FreeformEquationQuestionPractice question={question} /> </ContextProvider> ) console.log('freeform state: ', wrapper.childAt(0).instance().state) FreeformEquationQues ...