Looking for a way to locate the point where objects intersect in three.js?

My goal is to load 20 objects with random positions in a way that they do not intersect. How can I detect and check for intersections between these objects?

 for (var i = 0; i < 20; i++) {
        // Create a material
        var textureLoader = new THREE.TextureLoader();
        var map = textureLoader.load('./models/test_2.png');
        var material = new THREE.MeshPhongMaterial({ map: map });

        var shipMtl = new MTLLoader();
        var loader = new this.THREE.OBJLoader();

        shipMtl.load('./models/test.mtl', function(materials) {
            materials.preload();

            loader.setMaterials(materials);
            loader.load('./models/test.obj', function(object) {
                object.traverse(function(node) {
                    if (node.isMesh) node.material = material;
                });

                object.position.x = Math.random() * 500 - 250;
                object.position.y = Math.random() * 500 - 250;
                object.position.z = Math.random() * 500 - 250;
                object.scale.x = Math.random() * 2 + 40;
                object.scale.y = Math.random() * 2 + 40;
                object.scale.z = Math.random() * 2 + 40;
                object.rotation.x = Math.random() * 2 * Math.PI;
                object.rotation.y = Math.random() * 2 * Math.PI;
                object.rotation.z = Math.random() * 2 * Math.PI;
                var obj = object; // put your object as global
                scene.add(obj);
            });
        });
    }

    raycaster = new THREE.Raycaster();

    mouse = new THREE.Vector2();
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    this.refs.figure.appendChild(renderer.domElement);

Answer №1

I may have overlooked some details in the question, but here's a function that checks whether two objects intersect:

function checkIntersection(object1, object2) {
    /**
     * This function checks if two 3D objects intersect.
     * @param {THREE.Object3D} object1
     * @param {THREE.Object3D} object2
     * @returns {Boolean} 
    */ 

    // Performing bounding box intersection test
    let bbox1 = new THREE.Box3().setFromObject(object1);
    let bbox2 = new THREE.Box3().setFromObject(object2);

    const result = bbox1.intersectsBox(bbox2);

    if (result) { // The objects intersect.
        return true;
    } else { // The objects do not intersect.
        return false;
    }
}

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

The unhandled type error rises with each scroll I make

Having been diligently working on my current website project, I encountered a puzzling issue. Upon writing code to implement smooth scrolling throughout the site, I found myself facing a persistent error that continues to escalate with each scroll up or do ...

Error message: "Ajax script is failing to run"

Currently I am delving into the world of Ajax and have encountered a minor issue. I've been attempting to make a POST request to a Django backend using ajax, but strangely enough, the alert isn't showing up on screen. Furthermore, upon inspectio ...

The form I created retrieves select options via an ajax call, but after saving, the post values are not displaying as expected

I have created a form with the following HTML code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Populate City Dropdown Using jQuery Ajax</title> <script type="text/javascript" src="h ...

Switching to a different view in a React Native application

I am encountering difficulties while navigating between pages in my React Native application. Whenever I try to use the button, an error message pops up saying: TypeError: undefined is not an object (evaluating '_this.props.navigation'). My app c ...

Ways to compare UTC timestamps using JavaScript

Insight into Time Data I have obtained UTC start and end times from a database query, which are stored in an array format as follows: [ '9145001323', '08:00', '12:00' ] The second and third elements in the array indicate t ...

When trying to access the key value of a dynamically generated object, it returns as undefined

I am facing a challenge with my student object structure... { Freshmen: [{id: 3}, {id: 5}], Sophomores: [{id: 2}, {id: 6}], Juniors: [{id: 1}, {id: 8}], Seniors: [{id: 9}, {id: 4}, {id: 7}] } My goal is to retrieve full student objects from the d ...

Refreshing the page results in a 404 error when utilizing React Router

I am currently facing an issue with my web application setup. Back-End My back-end consists of a Node.js/express server that serves files in response to specific requests made to certain routes. Front-End On the front-end, I have React pages that commu ...

Change a space-separated string containing coordinates into an array of JavaScript objects

Here is a string separated by spaces: const coordinates = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604" Now, we want to convert it into an array of objects: const coordinatesArray = [ { lat: 42.44492, lng: 75.637764 }, { lat: 42.4455 ...

Utilize the id in AngularJS to bring attention to a specific row within a table

I am brand new to using angularjs. I currently have a table structured like this: HTML <table class="table table-striped" id="manageResumeTable"> <thead class="text-center text-info text-capitalize"> <th class="text-center col- ...

Creating a delayed queue using RxJS Observables can provide a powerful and

Imagine we have a line of true or false statements (we're not using a complicated data structure because we only want to store the order). Statements can be added to the line at any time and pace. An observer will remove items from this line and make ...

Issue with Redux-form's type prop not functioning as expected with checkbox and radio components

Hey there, I'm new to working with redux forms and I've been trying to figure out how to use input types other than "text". I've read through the documentation but for some reason, types like "checkbox" or "radio" are not showing up in the b ...

Sending Ajax data to a controller function

I am looking for guidance on how to pass values from my view to my controller using ajax. As someone who is new to working with ajax, I would appreciate some assistance in understanding the process. Full Page @model ALSummary.Models.MonthReport @{ ...

Executing a function within a VueJs 2 component immediately after it has finished loading

How can I retrieve data after a component has finished loading? When I initialize my Vue instance and load the component, the template loads correctly but the functions in the mounted lifecycle hook are not executed, causing the stats object to remain empt ...

How to solve the issue of synchronizing data fetching from a json-server and displaying it in the UI with React?

While working with json-server to retrieve data and display it in the UI, I often face a recurring issue that leaves me puzzled. The process of fetching data is asynchronous, which means that setting the state after fetching the data takes some time. As a ...

Error message while running jQuery 3.2.1: issues with UL and LI

I have a link that displays the desired outcome Despite using jquery version 3.2.1, when I insert my code into Dreamweaver cc 2018, it fails to work. On my jsfiddle, the selection is sorted alphabetically, but on my web page it is not. var mylist = $( ...

Placing an icon to the left of the primaryText within the <ListItem> component of Material UI

Seeking to enhance a <ListItem> from React Material UI that currently displays a checkbox on the left side. My goal is to insert an image or icon between the checkbox and the title, positioned to the left of the title. Upon reviewing the documentatio ...

Upon initiating npm start in my React application, an error was encountered: internal/modules/cjs/loader.js:834

Upon downloading my React course project, I proceeded to install dependencies and run npm start. To my dismay, I encountered the following error: PS C:\Users\Marcin & Joanna\Desktop\react-frontend-01-starting-setup> npm start &g ...

Obtain URL parameters prior to rendering with Next.js on the server side

Looking to retrieve the parameters from a URL coming from the Spotify API, for example: http//link.com/?code=examplecode. Is there a way to extract the value of "code" prior to rendering so that I can redirect it and transfer the code value to another p ...

How can you use plain javascript to drag and drop the cross sign within the box in the grid?

Creating a grid in HTML where clicking on a box will draw an x sign and remove it if clicked again. View the DEMO here. Challenge Description:- I am now looking to implement dragging the cross (x) sign to another grid within the box, but cancelling the ...

Struggling to retrieve data from Firebase in React Native?

It's been a challenge for me as a newcomer to React Native trying to retrieve data from a Firebase database. This is the process flow of how my data is handled: 1. A user selects locations and trip details (name, startDate, endDate) --> stored in ...