Detecting collisions between multiple moving objects in Three.js

Currently, I have several objects that are moving forward randomly using the following code:

model.lookAt(position_x, 0, position_z);

setInterval(function(){
   model.translateZ(0.015);
}, 10);

However, I am facing an issue where these objects might crash into each other during these movements. I came across a solution that suggests using bounding boxes for collision detection, but it only seems to work for collisions between two objects:

How to detect collision between two objects in JavaScript with Three.js?

My question is, is it possible to implement collision detection for multiple objects, each having their own set of collision parameters?

Thank you for your help!

Answer №1

To accomplish this task, follow these steps:

var objA = ...your initial object...
var objB = ...your second object...
var objC = ...your initial object...
var objD = ...your second object...

box1 = new THREE.Box3().setFromObject(objA);
box2 = new THREE.Box3().setFromObject(objB);
box3 = new THREE.Box3().setFromObject(objC);
box4 = new THREE.Box3().setFromObject(objD);

const boxes = [box1, box2, box3, box4];


// During each frame, use this code to check for collisions:
boxes.forEach(box => {
  // Exclude the current box from the list of boxes
  const otherBoxes = boxes.filter(other => other !== box)

  // Determine if any of the other boxes intersect with the current box
  otherBoxes.forEach(other => {
    if (box.intersectsBox(other)) {
      // Collision detected! Take action
    }
  })
})  

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

Interactive navigation through scrolling with PHP onchange event

I need help with a PHP-related issue. I have a list of products that are generated dynamically using PHP. When a user clicks on one of the items in the list, the products are sorted. I also want the user to be smoothly scrolled to a new section of the page ...

nodejs downloading a plethora of images

I am currently working on a project where I am generating URLs and extracting images from those URLs. For instance, I have an array object called urls ['abc.com/01.jpg', 'abc.com/01.jpg', ....... ] and similar URLs like that. My goa ...

Is there a way to determine if an array includes an integer value?

I've been attempting to iterate through an array to verify if it includes an integer, but I'm struggling to make it work and I'm not sure why. Is it necessary to use the map method? Here is my code snippet: let words = ['Dog', & ...

Explore various SVG paths by hovering to reveal or conceal different divs

Hi there, I'll do my best to explain clearly. If this question has already been asked, I apologize as I couldn't find an answer when searching. I've used SVG to create a map on my HTML webpage and it's looking great. I also have hidden ...

Iterating through a for loop in Angular2 to send multiple GET requests to a Django backend

Currently, I'm facing a challenge with performing multiple GET requests using Angular2 within a Django/Python environment. After successfully making an API request and retrieving a list of users to determine the current user's ID, I utilize a .f ...

Gathering the presently unfinished observables within a superior-level rxjs observable

As an illustration, let's consider a scenario where I have a timer that emits every 5 seconds and lasts for 10 seconds. By using the scan operator, I can create an observable that includes an array of all the inner observables emitted up until now: c ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

"Can anyone provide guidance on how to initiate a css 3d animation by clicking a button

Currently, I am developing a folding hide/show animation that can be triggered using Javascript. If you would like to take a look at the code and see a working example, please visit this link: You can also view just the gist here: https://gist.github.com ...

The surprising behavior of Rails rendering partials even when they are commented out has

I'm intrigued by how Rails 5 handles partials and if there might be a hidden problem I haven't encountered yet. On my current page, I have two partials - one that is included in the HTML itself, and another that is supposed to render inside an aj ...

Why is MutationRecord[] organized as an array in MutationObserver?

I've been diving into the world of MutationObserve, and I've grasped most of it. However, one thing that's puzzling me is why the parameter requires an array. According to the documentation: An array of MutationRecord objects, detailing e ...

Node Express JS: Efficiently handling multiple fetch responses before sending data to client

My goal is to call an API that only accepts one animal name at a time, but I receive the names of multiple animals in a query separated by commas. To achieve this, I plan to call the API once for each animal, push the JSON data into an array, and then resp ...

What could be causing the absence of req.body data in a specific route in my Node JS application?

Hello, I am encountering an issue with my Node JS application: When attempting to authenticate, I am receiving an "undefined" value for "req.body.username" upon sending a POST request to that specific route. This problem seems to only occur on this parti ...

Ways to extract a specific element from a webpage's body section

When utilizing node-fetch to retrieve the body of a site, I follow this process: import fetch from 'node-fetch'; (async () => { const response = await fetch('link'); const body = await response.text(); console.log(body) ...

The setTimeout function interrupts the event loop

Recently, I came across conflicting information regarding the usage of setTimeout to create nonblocking/asynchronous functions. One article suggested that using setTimeout is essential for this purpose, while another claimed that it actually blocks the eve ...

The useEffect function completely overwrites the existing store

My Redux store consists of 3 reducers: let reducers = combineReducers({ config: configReducer, data: dataReducer, currentState: gameStateRecuder}) let store = createStore(reducers, applyMiddleware(thunkMiddleware)); Initially, each reducer in the store i ...

Send form information using the REST method

Can someone provide guidance on how to properly handle this endpoint in my code? @PostMapping("/createUser") public ResponseEntity<User> createUser(@RequestBody User user) {...} I am looking to implement a user creation feature on my HTML ...

Steps for creating a JSON object to send batch emails using Mailgun

I am looking to dynamically create a JSON object named recipient-variables using two separate arrays - one for emails and the other for first names and IDs. How can I write JavaScript code to achieve this? 'recipient-variables': '{"[em ...

The useEffect alert is triggered before the component is re-rendered

Can someone help me understand why the HP in the code below is displayed as "1" when the alert is thrown, and only set to "0" after I confirm the alert? Shouldn't the component be rerendered before the alert is thrown so that it has already been displ ...

"Modifying the content:url() with JavaScript: A step-by-step guide

Hello, I am currently working on creating a traffic light using an array of images. My goal is to change the image path specified in the CSS when a button is clicked, to change the appearance of the traffic light. In this case, the 'content.url()&apos ...

What is the proper method for utilizing colspan within the footerData of a jqGrid?

Are you looking to customize the footer of your jqgrid as shown in the example below? I am trying to set up a custom footer for my jqgrid similar to the one displayed above. I have already enabled the footerrow:true option and used $self.jqGrid("footerDat ...