Issue encountered while attempting to animate a spherical object within a confined space in Three.js

I'm fairly new to three.js and encountering issues while attempting to animate a sphere moving through a space.

My approach involves creating a new sphere and using

new THREE.Vector3().randomDirection()
to set it in motion. The sphere is meant to move within a bounded sphere for collision detection. However, when I incorporate
ballbb.copy(ball.geometry.boundingSphere).applyMatrix4(ball.matrixWorld)
into the code to ensure the bounded sphere moves with the sphere, the motion of the sphere suddenly halts.

const sphere = new THREE.SphereGeometry(70);
const sphereMaterial = new THREE.MeshStandardMaterial
var ball = new THREE.Mesh(sphere,sphereMaterial)
ball.position.x = (Math.random() - 0.5) * 1000;
ball.position.y = (Math.random() - 0.5) * 1000;
ball.position.z = (Math.random() - 0.5) * 1000;

ball.userData.vel = new THREE.Vector3().randomDirection();

var ballbb = new THREE.Sphere(ball.position, 70)
scene.add(ball)

function animate() {

    requestAnimationFrame(animate)

    controls.update()
    render()
    ballbb.copy(ball.geometry.boundingSphere).applyMatrix4(ball.matrixWorld)
    console.log(ball.position)

}

function render() {
    renderer.render(scene, camera)
    ball.position.add(ball.userData.vel)
}

Answer №1

After spending some time debugging, I was able to discover the root of the issue. The story behind it is quite intriguing, so brace yourself...

When looking into the Sphere constructor (r152 source code), I found that it expects a Vector3 for the center position and a Number for the radius of the sphere being defined. The interesting part is that the center Vector3 is not duplicated into the Sphere.center, but rather simply assigned to the property. This means that Sphere.center will now refer back to the original Vector3 passed to it.

But hold on, there's more to it!

In the world of three.js, making changes to Mesh.position will not immediately update the matrixWorld unless you explicitly do so with Object3D.updatematrixWorld() or a call to render. Hence, until this update occurs, ball.matrixWorld will retain the matrix from the previous update.

Unraveling the chain of events...

  1. You set ball.position (which technically also updates ballbb.center!)
  2. You render the scene (which automatically triggers Object3D.updateMatrixWorld())
  3. You modify ball.position (no automatic update to ball.matrixWorld)
  4. You copy the geometry's bsphere (identity position) into ballbb
  5. You apply ball.matrixWorld to ballbb (this involves multiplying it against ballbb.center)
  6. Go back to step 1 and repeat

Evaluating the situation

Step 4 is where things start going awry. When you copy the identity bounding sphere into ballbb, you essentially undo the update made in Step 1, not only for ballbb but also for

ball</code! By copying the identity, you reset <code>ballbb.center
(and consequently, ball.position) to (0, 0, 0). Subsequently applying the ball.MatrixWorld results in applying the transformation from the previous frame since there hasn't been a render or an updateMatrixWorld since Step 2, hence the ball appears motionless.

How can this be resolved?

You could potentially rearrange your logic to ensure that updating ball.position or ballbb.center is both applied and propagated correctly. However, I managed to resolve it by making a single adjustment:

var ballbb = new THREE.Sphere(ball.position.clone(), 70)

Take note of the call to Vector3.clone(). This ensures that the Vector3 provided to the Sphere is a duplicate of

ball.position</code, ensuring that updates to one will not affect the other.</p>
<h3>A more effective solution...</h3>
<p>Ultimately, the ideal approach would be to simplify your code and refrain from performing any unnecessary calculations. When creating your <code>Sphere
, do provide it with ball.position, and then leave it at that. As you update ball.position, it will also update ballbb.center. Given that a Sphere lacks a matrixWorld, all computations are based on the center and radius values, resulting in the sphere "automatically" following ball.

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

JavaScript EasyBitConverter

Looking to create a basic C# BitConverter equivalent in JavaScript, I've developed a simple BitConverter implementation. class MyBitConverter { constructor() {} GetBytes(int) { var b = new Buffer(8); b[0] = int; b ...

Will terminating a Google Cloud Storage stream impact network usage?

As part of my project, I am developing a media server that will serve streamable audio files. To reduce the number of requests to Google Cloud Storage, I have implemented a caching system. However, one issue I've encountered is that Chrome sends two ...

Problem with resizing in CSS and jQuery

I need help creating a chatbox that can be resized. I've almost got it, but the bottom part of the chatbox detaches when I resize it. Also, I'm having trouble making the userList a fixed size that won't be affected by resizing. Check out th ...

Is there a way to display the next/previous buttons separately from the scroller in my jQuery thumbnail scroller implementation?

Is there a method to display the next and previous buttons outside of the scroller frame when using jQuery thumbnail scroller by manos.malihu.gr? I have attempted to modify the button class in CSS to make them more prominent or visible, but unfortunately ...

Updating a property value within a JSON object: Adjusting attributes in a JSON data format

How can I modify a specific key's value in a JSON array like the following example: input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}] ...

I am encountering an issue where propData in Vue Jest is returning as undefined

I have encountered an issue while passing the propData in my jest test file for a Vue component. It seems that the propData is not being set to the component and instead, I am receiving an error saying "cannot read property of clouds of undefined." Could i ...

What could be causing this highchart plot to fail to display in both IE and Chrome?

Check out the plot in this jsfiddle: http://jsfiddle.net/essennsee/y5HCm/ The plot looks good in Firefox, but only shows the legend in IE and Chrome. If I remove the following code snippet it works fine. Is there a different way to format the labels?: ...

Using Node JS to pass variables to the client

Currently, I am utilizing Node JS and Express for my server-side needs. In my server-side code, I pass a variable (sources) to my EJS template. Part of this variable is used to populate a list on the webpage. However, when a user clicks on an item in the ...

Steps to create two jQuery dropdown filters for multiple identifiers:

Is it possible to create two dropdown menus that can be used to filter a gallery of images? I am currently facing an issue where the filtering functionality is not working after adding a name attribute to the image IDs. When I select an option from the s ...

Learn how Angular 2 allows you to easily add multiple classes using the [class.className] binding

One way to add a single class is by using this syntax: [class.loading-state]="loading" But what if you want to add multiple classes? For example, if loading is true, you want to add the classes "loading-state" and "my-class". Is there a way to achieve t ...

Duplicate entries being saved in the database due to Ajax calls

I am currently utilizing Fullcalendar jQuery with PHP for managing events. I am making an AJAX call to add events, and while it works fine for the initial event entry after a page refresh, it starts creating duplicate events for subsequent entries. I am un ...

Tips for transferring a function from a Node.js server to a client

Hey everyone, I'm trying to achieve the following: On the Node server side: var fn = function(){ alert("hello"); } I am looking for a way to send this function to the client side. I am currently using AngularJS, but I am open to other solution ...

What is the best way to assign three different dates in my protractor test?

I am facing an issue with setting random dates in 3 date fields in a row using Protractor. The problem is that Protractor sets the dates too quickly and sometimes assigns invalid dates like: first data: 01/08/1990 (correct) second data: 01/09/0009 (inva ...

Error: Unable to assign values to undefined properties (specifically 'styles') when using withLess, withSass, or withCSS in next.config.js within Next.js

I have been attempting to set up a NextJS 12 project with custom Ant Design. Following some examples I found, it seems I need to configure my next.config.js file with the libraries @zeit/next-sass, @zeit/next-less, and @zeit/next-css. However, when I try t ...

Obtaining data from a callback function within a NodeJS application

There is a function in my code that performs a backend call to retrieve an array of names. The function looks something like this: module.exports.getTxnList = function(index, callback) { ....some operations ..... .... callback(null, respon ...

Response is sent by Sequelize Foreach loop before data is updated

My goal is to retrieve all content and media from a post, then append it to a new post before sending it as a response for easier access to the data. The issue I'm encountering is that the response is being sent before the content and media are fetche ...

What is the best way to retrieve a JSON key in ReactJS?

I am currently facing a rendering issue. In my componentDidMount function, I am using axios to make a GET call and then updating the state with the received JSON data. The problem arises when I try to access the keys of the JSON in the render method becau ...

Issue with Enter key not working on an individual textbox within Javascript/PHP chat functionality

Recently, I created a chat feature with text boxes that send messages when the ENTER key is pressed. However, I encountered an issue with it not working for the "Warning" functionality. Whenever I press Enter in this context, nothing happens. Can anyone pr ...

Error Message: Undefined Service in Angular version 1.5.4

I'm currently developing a sample application using AngularJS 1.5.4, built on angular seed, EcmaScript 6, and with a node.js web server. For routing, I am following the guidelines provided here: https://docs.angularjs.org/guide/component-router. Howe ...

Content Security Policy directive violation: Chrome extension policy error occured due to refusal to execute inline event handler

I've been working on a chrome extension to perform a simple task, but I've hit a roadblock with one line of HTML code that's causing issues with setting the correct permissions. Despite my efforts, I'm stuck on what exactly needs to be ...