How to find a collision between a spherical object and a triangular shape in a three

In my research, I am exploring the possibility of detecting collisions between a triangle and a sphere in three.js.

Currently, I have devised a method using the raycaster and the sphere's vertices. However, this approach has proven to be unreliable as there are cases where the triangle falls "between" two of the sphere's vertices, making it undetectable.

I am seeking a more accurate and robust mathematical algorithm to solve this problem.

Answer №1

Good day, I have come across the resolution :

The process consists of 2 main steps :

Step 1

I establish 3 lines by utilizing the 3 points available from the triangle :

 var line1 = new THREE.Line3(a,b);
 var line2 = new THREE.Line3(a,c);
 var line3 = new THREE.Line3(b,c);

 Subsequently, I identify the nearest point on each of these 3 lines to the sphere's center :
  
 var closestPoint1 = line1.closestPointToPoint(center, true);
 var closestPoint2 = line2.closestPointToPoint(center, true);
 var closestPoint3 = line3.closestPointToPoint(center, true);

 Following that, I compute the distance from that point to the center :

 // code for just 1 line

 var distToCenter = closestPoint.distanceTo(center);
 if(distToCenter <= radius){ 
   // a collision is present
 }

That concludes the examination of the lines surrounding the triangle. If no collision occurs with the sphere, I will then examine the interior of the triangle in Step 2 :

Step 2

I generate a THREE.Triangle using the 3 vertices of the triangle, proceed to create a plane based off that triangle, and ultimately locate the closest point from the plane to the center of the sphere . Detection of collision is confirmed if said point aligns with the triangle:

 var triangle = new THREE.Triangle( a,b,c );
 var plane = triangle.plane();
 var pp, cp;

 var dp = Math.abs(plane.distanceToPoint(center)); 

 if(dp <= radius){ 
   pp = plane.projectPoint(center);
   cp = triangle.containsPoint(pp);
      
   if(cp === true){
       // collision detected
   }
 } 

If no signs of collision are found in either Step 1 or Step 2, it implies there is no contact between the triangle and the sphere.

This approach has proven effective in my recent project.

Please do not hesitate to report any issues you might face.

Answer №2

Rather than relying solely on a flawless mathematical equation, I suggest taking a look at this helpful resource that specifically addresses the issue you seem to be facing: Three.js - Achieving precise ray casting for detecting collisions

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

Unable to load more than one controller in a single partial view using AngularJS

I am having trouble loading a second controller to populate a select in my view. Despite my efforts, it just won't cooperate. This is the code snippet I'm using: app.js (function() { 'use strict'; angular .module('app.lazylo ...

How can you efficiently pass multiple JSON files as arguments for Observable Arrays, especially when the values from one file are required for use in another file?

My goal is to utilize $.getJSON to retrieve data from two JSON files and assign their values to observableArrays. Currently, I have hard-coded the JSON data into the observableArray. You can view an example on this JSFiddle link. This was my initial appro ...

adhesive section on the left side with a defined lower boundary

I have a contact div that I made sticky using Bootstrap affix. <div id="contactForm" data-spy="affix" data-offset-top="400"> However, I am unsure of how to limit its bottom to the top of the next div. In other words, I want it to stay in place when ...

Similar Functionality to jQuery's .load() in REACT

I'm currently diving into the world of React, attempting to transition a PHP + jQuery Page to React (minus the jQuery). However, given the intricate complexity of the page, I won't be able to migrate everything at once. As a result, I need to sta ...

Having trouble installing memlab using the npm package

Recently, I made an attempt to install the memlab library from Meta's GitHub. Initially, when I installed it without using the -g flag, the installation was successful. However, I encountered an issue where I could not execute any of the memlab comman ...

The product has been taken out of the cart, yet it has not been reinserted into the cart

The product disappears from the cart after clicking on Add to Cart, but it doesn't reappear when clicked again. //function for adding only one item to cart document.getElementById('btn1').onclick = function() { addItemToCart() }; fun ...

What is the reason behind having to refresh my ReactJS page despite it being built with ReactJS?

I have developed a task management application where users can input notes that should automatically update the list below. However, I am facing an issue where the main home page does not display the updated todos from the database unless I manually refres ...

MongoDB suggests

I'm currently developing an app that requires autocomplete functionality for search. I've started implementing it using regular expressions (regexp), but I'm unsure if this is the optimal approach. Each new character input in the search bar ...

Enhancing React components with Hooks and markers

I'm facing a syntax uncertainty regarding how to update React state using hooks in two specific scenarios. 1) I have a state named company and a form that populates it. In the contacts section, there are two fields for the company employee (name and ...

The React server-side rendering isn't reflecting changes made on the client-side route

Upon the first refresh, both the server and client side are updated; however, subsequent updates only affect the client side when switching pages with react router. For instance, refreshing the page or entering a new URL causes changes on the server and t ...

How can we simplify deeply nested ajax callbacks in programming?

I have come across JavaScript code where the success callback of an Ajax handler triggers another Ajax call, which in turn may trigger yet another Ajax call. This results in deeply nested anonymous functions. Is there a smarter programming approach that ...

Encountered SyntaxError: An unexpected token has been found while integrating leaflet with flask

Despite adding all necessary scripts and configuring my API_KEY in config.js, I keep getting an error message saying "Uncaught SyntaxError: Unexpected token." I have double-checked my API key multiple times, and it seems to be correct. Here is a snippet f ...

Encountering Issues with File Uploads in Express.js with Multer

Currently, I am immersing myself in Node.js through the guidance of a book titled "Web Development with Nodejs and MongoDB." However, I have hit a roadblock when attempting to upload an image using Multer. The code snippet causing me trouble is as follows: ...

webpack: the necessity of running TSC before resolving modules manually

Below is my complete webpack.config.js file for reference. If I delete all the *.js files in the app directory, webpack throws the following error: ERROR in ../main.ts Module not found: Error: Can't resolve './app/app.module' in 'C ...

Executing the executeScript method in Microsoft Edge using Java and WebDriverWould you like a different version?

I'm currently attempting to execute the following code in Microsoft Edge using WebDriver ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals(&quo ...

Strange rendering in CSS JQuery Datatable

I am encountering an issue with a DataTable from datatables.net. Each row can be selected by clicking on a checkbox, which triggers a click event. In response to the event, I add or remove a CSS class to change the appearance of the selected rows. $(".cbD ...

Implementing the OnClick method for the button component

After successfully creating a reusable button component, I now want to assign different onClick links to each Button component. How can I achieve this? import styled from 'styled-components' const Button = styled.button` background: #0070f3; ...

Enhancing jquery datatable functionality with data-* attributes

I successfully added an id to each row of my data table using the rowId property, as outlined in the documentation. $('#myTable').DataTable( { ajax: '/api/staff', rowId: 'staffId' } ); Now I am wondering how I can ad ...

eliminating various arrays within a two-dimensional array

I need help with a web application that is designed to handle large 2D arrays. Sometimes the arrays look like this: var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]]; I am looking to create a function that will remove any array ...

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...