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.