Skip to content Skip to sidebar Skip to footer

Adding Number Of Cubes In Three.js

I am trying to add a number of spheres in the following example. Initially it had only three cubes, but I need to add some 10 spheres that would be equidistant from each other and

Solution 1:

Missing 4th Sphere

You specify:

pivot1.rotation.z = 0;pivot2.rotation.z = 2 * Math.PI / 3;pivot3.rotation.z = 4 * Math.PI / 3;pivot4.rotation.z = 6 * Math.PI / 3;

6 * Math.PI / 3 = 2 * Math.PI

Note, three.js uses radians, therefore 2 * PI is 0 (a full revolution is the same place as no rotation.

So pivot1 and pivot4 have the same effective rotation and your 2 sphere end up in the same place in space.

Speed

You currently handle speed by mutating the z rotation on every frame.

parent.rotation.z += 0.01;

This obviously works just fine for a demo. You can speed it up by moving more per frame (or getting more frames, ie better machine or other upgrades)

parent.rotation.z += 0.04;

Now it rotates at 4 times the speed!

More Spheres

Once you get past working with counts larger than your number of fingers on a hand, I recommend getting generic with arrays. Instead of listing out pivot1, pivot2, pivot3, . . . pivot0451, generate this with a loop. (Functionally you could use ranges if you prefer).

First, we declare how many spheres to make. Then divide up the circle (2 * Math.PI radians to go around). Then for ever sphere, make a pivot. Then, for every pivot, add a mesh. And you're done.

var numberOfSpheres = 10;
var radiansPerSphere = 2 * Math.PI / numberOfSpheres;
// pivotsvar pivots = [];
for (var i = 0; i < numberOfSpheres; i++) {
  var pivot = newTHREE.Object3D();
  pivot.rotation.z = i * radiansPerSphere;
  parent.add(pivot);
  pivots.push(pivot);
}

var meshes = pivots.map((pivot) => {
  var mesh = newTHREE.Mesh(geometry, material);
  mesh.position.y = 5;
  pivot.add(mesh)
  return mesh;
});

I implemented this at this codepen.io

Happy coding.

Post a Comment for "Adding Number Of Cubes In Three.js"