Hello everyone!
I modified a PG (originally created by @Raggar) so that 5 grey spheres follow 5 textured spheres when the distance between them is less than 2.
https://www.babylonjs-playground.com/#TXATGH#1
However, it seems that the grey spheres are only following specific textured spheres, and not simply any textured sphere that is within 2 units.
The goal is to get any grey sphere to follow any textured sphere based on the distance rule.
Hi Anderson34,
Essentially all you need to do is just check to see which sphere is closest, then follow that. The logic in the Playground appears to be laid out a bit differently that I would have immediately expected, but I believe you’re correct that each sphere in sphere2Array
attempts to follow a specific sphere from sphereArray
, based on index. To get them to follow the closest spheres, all you should need to do is switch from having sphere2Array[i]
's movement based on sphereArray[i]
's movement to something more along the lines of the following.
sphere2Array.forEach(sphere2 => {
var distSq = -1;
var tempDistSq;
var nearSphere;
sphereArray.forEach(sphere => {
tempDistSq = BABYLON.Vector3.DistanceSquared(sphere.position, sphere2.position);
if (distSq < 0 || tempDistSq < distSq) {
nearSphere = sphere;
distSq = tempDistSq;
}
});
// nearSphere now points to the closest element in sphereArray to sphere2
// Follow logic can now be performed here.
});
For more complicated scenarios you can do more complicated things to make this more efficient and fancy, but for a constrained case like this the above logic (or something along those lines) should be more than adequate. Hope this is helpful, and best of luck!
1 Like
Hello @syntheticmagus, and thanks for taking a look at this! I’ll work on incorporating this code into my project.
Thanks again!
1 Like