Unable to identify collision in JavaScript's 3D environment

I'm currently using three.js to develop a simulation of Brownian Motion, but I've hit a roadblock when it comes to getting the tiny molecules to collide with each other. This is the snippet I have at the moment:

function intersects(sphere, other){  
    var distance = Math.sqrt((sphere.position.x - other.position.x) * (sphere.position.x - other.position.x) +
                             (sphere.position.y - other.position.y) * (sphere.position.y - other.position.y) +
                             (sphere.position.z - other.position.z) * (sphere.position.z - other.position.z));
    if(distance < 4){
         return true;
    } else {
         return false;
    }
}

function checkCollision(current){
    for(var i = 0; i < balls.length; i++) {
        if(intersects(balls[current], balls[i]) == true){
//          balls[current].velocity.negate();
            alert('hey');
        }
    }
}

Even though the code is running, none of the balls seem to actually collide or intersect with each other, yet an alert box keeps popping up. I tried checking if the distance was less than (sphere.radius + other.radius), but that didn't work either. Keeping it '< 4' does affect performance, causing it to drop to around 5 fps or lower. The checkCollision function is executed every frame during the animation.

function animate(){
    for(var i = 0; i < balls.length; i++){
        balls[i].position.add(balls[i].velocity);
        checkWallBoundaries(i);
        checkCollision(i);
    }

    THREEx.WindowResize(renderer, camera);
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
    controls.update();
    stats.update();
}

I'm stuck on why this collision detection isn't functioning properly. Any assistance would be greatly appreciated.

edit: After uncommenting the balls[current].velocity.negate() line, this is what happens . The balls oscillate back and forth, but they're nowhere near each other. It's puzzling as to why collisions are being triggered in this scenario.

Answer №1

Each sphere interacts only with other spheres. Make sure to specify i !== current

for(let i = 0; i < spheres.length; i++) {
    if(current === i) continue;
    if(checkOverlap(spheres[current], spheres[i]) == true){
        notification('collision detected');
    }
}

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

Looking to minimize the amount of HTML code in Angularjs by utilizing ng-repeat

Working with some HTML <tr class="matrix_row" ng-repeat="process in matrixCtrl.processes | filter : { park: parentIndex } track by $index"> <td class="properties" ng-click="dashboardCtrl.currParam=0; dashboardCtrl.currentProcess=process"> ...

Why doesn't Material-UI seem to understand the theme.spacing function?

Issue with Material-UI's theme.spacing function I've encountered a problem while using Material-UI's theme.spacing function in a React application. It seems that the spacing function is not being recognized. The Javascript error message st ...

Receiving an error while trying to install packages from the NPM registry due to non

I am facing some challenges while attempting to install my Ionic App through the registry along with its dependencies. I have been using npm i --loglevel verbose command, and my ~/.npmrc file is configured as follows: //nexus.OMMITED.com/repository/:_auth ...

What is the best way to adjust image size based on different screen sizes while ensuring the buttons at the top remain responsive

How can I make the image and image select and delete buttons responsive? I am looking to eliminate the gap after the delete button. Any suggestions are welcomed. <div class="container mt-0"> <div class="row"> ...

Looping through properties of objects with the help of angularJS ng-repeat is known as using objects['propertyname&#

What is the best way to iterate over an object with property names like this? $scope.myobjects = [ { 'property1': { id: 0, name: 'someone' } }, { 'property2': { id: 1, name: ' ...

Using Regex to replace special characters in TypeScript

I need assistance in removing the characters "?" and "/" from my inner HTML string. Can you guide me on how to achieve this using regex? For example, I would like to replace "?" with a space in the following content. "Hello?How are you?<a href="http:/ ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

Tips for enhancing the functionality of components within Vue

My expertise lies primarily in React, and I'm now exploring the Vue-centric approach to achieve the following: I want to enhance this component: , so that the label-position is set to top on mobile devices and left on desktop. However, I'm not s ...

A declaration file in Typescript does not act as a module

Attempting to create a TypeScript declaration file for a given JavaScript library my_lib.js : function sum(a, b) { return a + b; } function difference(a, b) { return a - b; } module.exports = { sum: sum, difference: difference } my_lib.d.ts ...

Exploring the use of Rails and jQuery to automatically update data through the use of setTimeout and ajax calls

There's a specific page accessible in the browser at "/calendar" that directs to "calendar#index". Utilizing a javascript setTimeout function, I'm attempting to re-fetch and update data on my page using $.get ajax method. $.get("<%= calendar ...

How can I add a channel to a category using await(discord.js)?

Having trouble organizing a new channel within a category. The .setParent(categoryID) method seems to only work with existing channels, causing an issue when I attempt to execute my code. Take a look at the code snippet below: client.on("message" ...

Unable to access image from JSON within Mobile Angular Ui utilizing Angular Js

Currently, I am able to retrieve various data from JSON such as Price and Display Order, but I am facing difficulty in fetching the image. HTML: <div ng-controller="chooseProductDescription"> <div ng-repeat="cat in productDescrip ...

My div does not refresh when using .load

I implemented ajax to retrieve the start time and end time from another page, and used setInterval to call this function every second like so. setInterval(function () { CheckTime() }, 1000); function CheckTime() { $.ajax({ url: "Get_TIme. ...

There was an issue locating a declaration file for the module 'clarifai'

https://i.stack.imgur.com/PgfqO.jpg I recently encountered a problem after installing the Clarifai API for a face recognition project. Despite my efforts, I have been unable to find a solution. When I hover over "import clarifai," I receive the message: ...

Unable to identify the element ID for the jQuery append operation

After attempting to dynamically append a textarea to a div using jQuery, I encountered an issue. Despite the code appearing to work fine, there seems to be a problem when trying to retrieve the width of the textarea using its id, as it returns null. This s ...

Browser refresh not triggering view update in Rails and ReactJS application

Recently, I integrated Reactjs into my Rails application. Strangely, when I modify the content of a .jsx file and reload it with different text, such as changing from <h1>Hello<h1/> to <h1> Hello again<h1/>, the browser fails to res ...

Incorporate a stylish gradient background into react-chartjs-2

I am currently working on adding a gradient background with some transparency to a radar graph within a react component. So far, I have only found solutions that involve referencing a chartjs canvas in an html file, but none for implementing it directly in ...

The React.js Mui Collapse component exclusively triggers animation during the transition while closing, without any animation when expanding

Whenever I implement the Collapse component from Mui library in my projects, I face an issue where the transition animation only works when closing the component (when in={false}). However, when opening the component, there is a delay before the animation ...

emulating the behavior of a synchronous XmlHttpRequest

While I have taken the time to explore similar questions like Pattern for wrapping an Asynchronous JavaScript function to make it synchronous & Make async event synchronous in JavaScript, I want to ensure that I consider all potential solutions. Is it ...

Is there a way to ensure that all asynchronous functions have finished executing before assigning them to module.exports?

Currently, I am working on developing an app that generates routes based on data retrieved from a MongoDB database using Mongoose. Here is the current setup: var app = express(); var articleRoute = require('./article.js'); var Articles = requi ...