Placing an object on the center of the screen

Hello,
I am trying to place an object at the center of the screen using scene.pick

But I do not see my object (sphere) at the center of the screen and I am getting the following error in the debug console (firefox)
Uncaught TypeError: can’t assign to property “_isDirty” on “{X: 0 Y: 5.000000119209275 Z: -9.000000357627826}NaN”: not an object

Please let me know what I am doing wrong

thank you

sphere.position = pickResult.ray.origin + pickResult.ray.direction * distance;

IMO should be:

  • (Vector3 + Vector3) * number
const position = origin.add(direction).scale(distance);

I did a little change:

  • onPointerDown set sphere to center
  • you can move the camera while pointer is pressed down
2 Likes

Hi, i have made an example but without scene.pick https://playground.babylonjs.com/#FVJT5H#4

maybe this will suit you

2 Likes

You can also place the mesh as a child of the camera to always stay in front:

sphere.parent = camera
sphere.position.z = 10;
2 Likes

@ZGltYQ and @Asdrubal Thank you - both your solutions indeed solve my issue with placing an object and let me move forward though I am still curious how scene.pick is supposed to work

1 Like

scene.pick works (look my first link). The problem is the sphere.position:

pickResult.ray.origin + pickResult.ray.direction * distance;
// {X: 0 Y: 5.000000119209275 Z: -9.000000357627826}NaN

without distance:

pickResult.ray.origin + pickResult.ray.direction;
// {X: 0 Y: 5.000000119209275 Z: -9.000000357627826}{X: 0 Y: -1.1923310911857404e-7 Z: 0.9999999999999929}

Should be something like:

origin.add(direction).scale(distance);

To get a new Vector3

2 Likes

@Asdrubal
Thank you for tips. Now it works - we need first scale the direction then add it to the origin. So I replaced

origin.add(direction).scale(distance);

with

        let scaledDir = direction.normalize().scale(distance);       
        sphere.position = origin.add(scaledDir)

Here is the working playground

1 Like

Perfect :+1:

Here’s another test to set on pointer up

1 Like

you can also do this so that an object is always facing the camera regardless of its orientation…

scene.activeCamera.getFrontPosition(4);

1 Like

@Dad72
I checked camera API Camera | Babylon.js Documentation
I do not see getFrontPosition position there. What is its input argument?

You probably missed it. It exists.

Here is a use in a PG :

2 Likes

@Dad72
Thank you! I was looking for it in Camera, but it is in TargetCamera