Manipulating multiple entities simultaneously in three.js

I am currently facing a challenge in three.js where I am attempting to move multiple balls simultaneously. I have created a function that generates a ball and used it to create three different balls. However, when I try to move all the balls together using another function, only one ball moves while the rest remain stationary. Any assistance on this issue would be greatly appreciated. Below is the code snippet:

Ball Function:

function Ball(valuex, valuey, valuez, ballname, color)
{
   var balMaterial, balGeometry, balMesh;
   balMaterial = new THREE.MeshLambertMaterial({ color: color});
   balGeometry = new THREE.SphereGeometry(0.3,50,50);
   balMesh = new THREE.Mesh(balGeometry, balMaterial);
   balMesh.position.set(valuex,valuey,valuez);
   balMesh.name = ballname;
   balMesh.ballDirection = new THREE.Vector3();
   balMesh.ballDirection.x = -5;
   balMesh.ballDirection.z = 1;
   balMesh.ballDirection.normalize();
   balMesh.moveSpeed = 25;
   scene.add(balMesh);
}

Move Balls Function:

function moveBalls (ball) {
var tempbal = scene.getObjectByName(ball);
var ballDirection = tempbal.ballDirection;
tempbal.position.add(speed.copy(ballDirection).multiplyScalar(clock.getDelta() * tempbal.moveSpeed));

    if (tempbal.position.x < -4.7) {
        ballDirection.x = Math.abs(ballDirection.x);
    }
    if (tempbal.position.x > 4.7) {
        ballDirection.x = -Math.abs(ballDirection.x);
    }
    if (tempbal.position.z > 12.2) {
        ballDirection.z = -Math.abs(ballDirection.z);
    }
    if (tempbal.position.z < -12.2) {
        ballDirection.z = Math.abs(ballDirection.z);
    }
    if (tempbal.moveSpeed > 0) {
        tempbal.moveSpeed = tempbal.moveSpeed - 0.002;
    }
}

Create Balls:

Ball(0,4.5,0, "ball1", 0xffffff);
Ball(2,4.5,0, "ball2", 0xffffff);
Ball(0,4.5,6, "ball3", 0xff0000);

Animate Scene:

function animateScene()
{
    moveBalls("ball1");
    moveBalls("ball2");
    moveBalls("ball3");
    requestAnimationFrame(animateScene);

    renderer.render(scene, camera);
}

Note: This is my first post here, so please let me know if there are any mistakes so that I can learn from them.

Answer №1

When using the clock.getDelta() function, keep in mind that it returns the seconds elapsed since the last invocation of clock.getDelta(). This means that only the first ball will be able to move initially. The first ball triggers a non-zero value when calling getDelta(). However, when attempting to move the 2nd and 3rd balls within the same frame, they receive a delta time of 0.

To ensure smooth movement for all balls, consider implementing the following logic:

function moveBalls (ball, deltaTime) {
    var tempBall = scene.getObjectByName(ball);
    var ballDirection = tempBall.ballDirection;
    tempBall.position.add(speed.copy(ballDirection).multiplyScalar(deltaTime * tempBall.moveSpeed));

    if (tempBall.position.x < -4.7) {
        ballDirection.x = Math.abs(ballDirection.x);
    }
    if (tempBall.position.x > 4.7) {
        ballDirection.x = -Math.abs(ballDirection.x);
    }
    if (tempBall.position.z > 12.2) {
        ballDirection.z = -Math.abs(ballDirection.z);
    }
    if (tempBall.position.z < -12.2) {
        ballDirection.z = Math.abs(ballDirection.z);
    }
    if (tempBall.moveSpeed > 0)
    {
        tempBall.moveSpeed = tempBall.moveSpeed - 0.002;
    }
}

// ...

function animateScene()
{
    var deltaTime = clock.getDelta();
    moveBalls("ball1", deltaTime);
    moveBalls("ball2", deltaTime);
    moveBalls("ball3", deltaTime);
    requestAnimationFrame(animateScene);

    renderer.render(scene, camera);
}

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

Using AXIOS and VueJs to visually represent data with a two-dimensional array

I'm new to vuejs and I want to display my data response in a two-dimensional table. This is the data I have: [{ "origine": "", "nb": 15 }, { "origine": "?", "nb": 18 }, { "origine": "?L", "nb": 1 }, { "origine": "G", "nb": 298 }, { ...

Malfunction of VueJS single-page application on WordPress admin menu page

The VueJS project was created using the Webpack template in vue-cli. When building for production, a static folder is generated with 2 subfolders and an index.html file. The subfolders include css and js, with one css file and three javascript files - app. ...

Expand the accordion and incorporate both a hyperlink and an anchor tag within the content

My go-to source for codes is usually https://www.w3schools.com. They also provide an accordion feature along with the code; However, I've encountered an issue where when a link is used -> to The accordion doesn't open but remains closed. Does ...

Is coffeescript supported by Moovweb?

Lately, I've been researching the Moovweb platform and I'm curious about its compatibility with CoffeeScript. Could someone share a code example to demonstrate how Moovweb works with CoffeeScript? ...

How can I show a hidden <td> with a codeMirror text area when a button is clicked and its display property is set to none?

I'm currently facing some difficulties with my project. I am working on a button that, once clicked, triggers a JavaScript function called ShowColumn() to display a hidden table column. This initially hidden column will become visible when the user se ...

Tips for selecting a specific input field in a ReactJS component with multiple inputs

I am currently developing a ReactJS application where I have implemented a component responsible for generating an HTML table. Within this component, I utilize Map to create rows using a child component. These rows contain multiple input fields that users ...

Adding a custom source to the script tag in Angular 7

I am currently using angular cli to develop my web application. The app is being built in the dist folder as of now. This is the index.html file: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Adm ...

Form submission is failing due to a single checkbox not being submitted and an error is occurring with MultiValueDictKeyError during

<body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/"> {% csrf_token %} <div class="form-group" ...

Adjust the height of the container div for the carousel according to the length of the text displayed

My image carousel features description content positioned on the right for wide-screen windows. However, I want the description to shift below the images when the browser window reaches a certain breakpoint. The challenge I am facing is that the height of ...

Using jQuery to insert a <li> element doesn't seem to be functioning as expected

Here is a snippet of code that I'm trying to work with: <ul class="vertical-tabs-list"> <li class="vertical-tab-button first selected">blah</li> <li class="vertical-tab-button">blah</li> </ul> I am attempting ...

Ensuring the correct range with HTML TextBoxFor

Is there a way to validate user input in a TextBoxFor to ensure it is less than a certain number at run-time? Here is the current code snippet for reference - <div class="col-md-3 input-group"> <span class="input-group-addon ...

What is the best way to add a background image to the title page in reveal.js?

Struggling with inserting a background image on the title page? Previously using io_slides for rmarkdown presentations made it easy. Just a few lines of code in the CSS file were needed to add a background image for both the title page and subsequent pages ...

How can I make the font of expandable TreeItems bold in a TreeView?

When iterating through an object and converting the key/value pairs to Material-UI TreeItems, is there a method to apply custom styling (such as setting the font-weight to bold) to expandable TreeItems? ...

Guide: "Executing an AJAX button click using a Greasemonkey script"

(find below a solution) I created a Greasemonkey script that automatically clicks on a specific link within a target website. Initially, my script looked like this: var MyVar = $("a:contains('Save')"); if (MyVar && MyVar.length) win ...

Can I simultaneously utilize submit and ajax functions?

As I work on CRUD for our website, the approach we are taking involves using submit. However, there are occasions where I need to pass data from a JS file to my controller (I am using Codeigniter). I am now considering whether it is common practice to do ...

The conditional statement in the given code snippet is failing to execute properly

const checkCondition = (props) => { let conditionMet = false; console.log('-----****----',props); if(props && props.isAllowed) { conditionMet = true; } if(someOtherCondition) { return( <li><Link className=" ...

In Internet Explorer 8, the functionalities of jquery animate() and slideUp() are not functioning properly

When it comes to animating the rows of a table using jQuery, I encountered an issue with IE8. While the animation works smoothly in FF, Safari, and Chrome, it fails to function in IE8 without showing any error messages for debugging purposes. To work arou ...

What is the best way to implement a conditional data-attribute tag in order to trigger JavaScript functionality?

Is there any way to conditionally apply JavaScript or jQuery code in an HTML Template? For example, if a data-id attribute with the value "no-copy" is found inside the body tag, certain JavaScript code will be applied. To explain it more simply, I have J ...

React's back button is experiencing functionality issues

I'm having an issue with my quiz page where the previous button is not functioning properly. The user should be able to change their answer before submitting, but after 5-6 clicks on the previous button, they are redirected to the next page without co ...

What is the most effective way to retrieve the inner HTML of an HTML tag using JavaScript or jQuery?

Let's consider the following code snippet: <p class="question"> this is my paragraph <p> And i'm inside tag in question class <h1> And this is my heading</h1> </p> </p> Now, the challenge is t ...