Face Closest Mesh?

Hello everyone,

In the PG below, the grey spheres will follow the textured spheres when within range.

https://www.babylonjs-playground.com/#SD6H29#1

Here’s the issue I’m having trouble resolving:

The grey spheres should always move forward along their z-axis (their “eyes,” blue axis). When they “see” a textured sphere, they should rotate to face the textured sphere as they move toward it. In other words, the “eyes” should always be facing the center of the closest textured sphere.

I tried the code the below, but my main project has about 400 objects moving around, and the frame rate was cut in half (about 30 FPS). Also, the grey spheres don’t always face the textured spheres correctly.

 var spherePosition = sphere.getPositionExpressedInLocalSpace();
		 
 sphere2.lookAt(spherePosition);

I’m not sure if there is a way to achieve this effect without seriously impacting scene performance.

Any suggestions would be greatly appreciated! :smiley: :+1:

I think lookat expect a world position. you should try to use spere.position instead.
also take care of the distance between sphere and sphere2 if the position are almost the same, you will get jittered matrix values. this is known as gimbal lock : Gimbal lock - Wikipedia

By default, transformNode.lookAt wants a position in local space relative to the space of the transformNode. Since all of the spheres don’t have a parent, local space and world space mean the same thing. The getPositionExpressedInLocalSpace function is a misnomer. It really means getPositionExpressedInObjectSpace. You don’t need to use this function. You can in this case just use position directly.

https://www.babylonjs-playground.com/#SD6H29#2

Thank you both @Cedric and @bghgary for taking a look at this, I really appreciate it!
I had no idea that sphere.position by itself was even an option to call for all coordinates (as opposed to sphere.position.x, etc.).

Thanks again! :smiley: :+1:

1 Like