Detecting when an object exits the proximity of another object in ThreeJS

In my ThreeJS project, I have planes (Object3D) flying inside a sphere (Mesh).

My goal is to detect when a plane collides with the border of the sphere so that I can remove it and respawn it in a different location within the sphere.

I am wondering how I can accurately determine when one object exits another object?

This is the current code I am using:

detectCollision(plane, sphere) {

  var boxPlane = new THREE.Box3().setFromObject(plane);
  boxPlane.applyMatrix4(plane.matrixWorld);

  var boxSphere = new THREE.Box3().setFromObject(sphere);
  boxSphere.applyMatrix4(sphere.matrixWorld);

  return boxPlane.intersectsBox(boxSphere);

}

Within my render function:

var collision = this.detectCollision(plane, this.radar)
  if (collision == true) {
    console.log("the plane is inside the sphere")
  }
  else {
    console.log("the plane is outside the sphere")
  }
})

The issue I am facing is that when the planes are inside the sphere, I consistently receive both true and false results until all planes have exited the sphere. At that point, I only get false and no more true indications.

Answer №1

Box3 is not recommended for calculating collisions between spheres and planes because it does not account for the curvature of the sphere or the rotation of the plane.

In Three.js, there is a handy class called THREE.Sphere that better suits your needs. It's important to note that this class serves as a mathematical tool rather than a visual representation like a Mesh with a SphereGeometry. You can utilize its .containsPoint() method in the following way:

var sphereCalc = new THREE.Sphere( center, radius );
var point = new THREE.Vector3(10, 4, -6);

detectCollision() {
    var collided = sphereCalc.containsPoint(point);

    if (collided) {
        console.log("Point is in sphere");
    } else {
        console.log("No collision");
    }

    return collided;
}

To detect collision with a plane, you will need to apply transformations and check all 4 points of each plane within a loop. While there is a Sphere.intersectsPlane() method available, be cautious as it uses an infinite plane for calculations instead of one with specified dimensions.

Edit:

It's worth mentioning that each plane typically consists of 4 vertices, so you must iterate through each vertex using a for() loop to check if the sphere contains each of these points.

Moreover, since the plane may have undergone transformations such as movement and rotation, its original vertex positions are likely transformed using a matrix. Here's an example of how to account for this in your calculations:

point.copy(vertex1);
point.applyMatrix4(plane.matrixWorld)
sphereCalc.containsPoint(point);

point.copy(vertex2);
point.applyMatrix4(plane.matrixWorld)
sphereCalc.containsPoint(point);

// ... continue for other vertices

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 Three.js environment experiences lag and a decrease in performance

In the threejs scene, there is a sphere geometry and a plane geometry. The sphere is textured with an image, while the plane geometry is textured with 2D text. The plane geometry is also attached with a click event. When clicking on the plane geometry, ...

Tiny adjustment to jQuery Collapsible Panel

I have successfully implemented a jQuery Accordion in my demo. When I click on 'About Us', it reveals the 'Team' link below. Exciting! Now, I am wondering if it is possible for this Accordion to function without needing the 'item& ...

Using Selenium to interact with a link's href attribute through JavaScript

New to Java and Selenium, I'm facing difficulties when trying to click on a link with JavaScript in href attribute. Here's the snippet from the page source: href="javascript:navigateToDiffTab('https://site_url/medications','Are y ...

Check the validity of a watched variable's value and block any assignments that do not meet the specified requirements without triggering the watch function

Check out my jsBin snippet here I am experimenting with watching a variable's value and handling failed validation by returning its previous value without triggering the watch function again. I am considering the following scenario: If validation ...

Displaying Material UI textboxes in multiple columns for dynamically created forms using ReactJs from an array

I am working with an API to retrieve a list of cars, and I have come up with the following code snippet to generate labels and textboxes for editing the car codes. {!carQuery.loading && carDefinitions?.map((car: ICarType, idx: number ...

Choose the grandparent of an element's parent

Is there a way to select the grandparent element of a child in Javascript without having to chain the .parentElement method twice? Specifically, I am looking for a method that can substitute .parentElement.parentElement when selecting the desired element, ...

How to add 1 to the final element in a JavaScript

I'm currently working on a task that involves incrementing the last element in an array using pop() and push(). However, I'm facing an issue where the original values are being retained after I try to increment the popped array. The objective is ...

What is the purpose of using double % in Java or JSP?

Yesterday, while reviewing some code, I came across a line that seemed very peculiar to me. In a JavaScript function, there is a condition checking for a string passed as a parameter in the following manner: "%%unsubscribe%%". See the snippet below for re ...

Storing an image in MongoDB using Multer as a file from Angular is not working as anticipated

I'm currently dealing with an issue that I believe is not functioning correctly. I installed a library in Angular called cropper.js from https://github.com/matheusdavidson/angular-cropperjs. The frontend code provided by the developer utilizes this li ...

Transforming jQuery code to pure vanilla Javascript

For my project, I decided to convert my jQuery code into native JavaScript. The goal is to eliminate the dependency on jQuery and achieve the same functionality. The current setup involves two pages - page.html and side.html. The page.html document fetches ...

Issue in JavaScript / D3.js: When button is clicked, data fails to update and instead new positions are plotted

When the user clicks a button, both the red woman (unvaccinated) and the blue woman (vaccinated) should be updated to reflect the new value. At present, when the button is clicked, the red woman updates correctly but the blue woman is recreated in the loca ...

Obtaining the local IP address of my system with React JS

Is there a way to retrieve the local IP of my computer within a React JS application? I would appreciate any suggestions on how to accomplish this. ...

Tips for inputting information without redundancy after selecting a specific designation

I'm experiencing a challenge with this code as it repeats when already chosen. My goal is to add data in the database once something has been selected. When I click on spin, the randomizer will choose a name and update their status to "done". Subsequ ...

Loading Webfonts Asynchronously in NextJS Using Webfontloader

I am currently working on a NextJS app where I am using webfontloader to load fonts dynamically. function load() { const WebFont = require("webfontloader"); WebFont.load({ google: { families: fonts } }); } However, I ha ...

Need assistance with creating a handle shape using ThreeJS

I need to design this unique handle shape in ThreeJS: https://i.sstatic.net/T57F0.jpg The handle shape I have envisioned consists of a combination of a plane geometry and twisted/squashed cones at each end with a smaller z position compared to the rest o ...

Utilizing an argument in the mapStateToProps function

This component features a counter along with two buttons for incrementing and decrementing the count. class App extends Component { render() { return ( <div className="App"> <h1>{this.props.counter}</h1> <b ...

Fetching information from server proves to be sluggish within AngularJS application

In the process of developing a web application, I am faced with the task of sending numerous $http requests to the server. My front-end is built using AngularJS while the back-end utilizes ExpressJS. The $http requests are currently being made as shown in ...

Tick the checkboxes if they are found in the JSON data

After parsing this JSON object: [{"id_distrib":"1"},{"id_distrib":"44"},{"id_distrib":"4"}] I need to select the following checkboxes: <input id="1" class="cb_distrib_linux" type="checkbox"value="1">Achlinux <input id="2" class="cb_distrib_lin ...

Having trouble with jQuery after adding more content?

I recently started delving into the world of javascript, incorporating it into my website. Just last week, I came across a script that utilizes jQuery to load extra content onto my page. Initially, everything seemed to be functioning smoothly until I reali ...

Using the OR operator in a JSON server

One way to retrieve data from a json-server (simulated server) is by using the following call: http://localhost:3000/posts?title_like=head&comments_like=today When this call is made, records will be returned where the title is similar to "head" AND c ...