Ray doesn't work when using camera position/target

Ref: Babylon.js Playground

For an ArcRotateCamera, creating a ray doesn’t seem to work unless the vector3 is cloned. I was wondering if this is the correct behavior or a bug? If this is the correct behavior, is there a guiding principle for when vectors should be cloned?

            const ray = new BABYLON.Ray(
                // This doesn't work:
                // Instead the following works:
                // camera.position.clone(),

Other Notes:

  • called in beforeRender method
  • I know that it’s also possible to use ‘scene.CreatePickingRay’ to do what I am doing, I am just experimenting.

Welcome aboard!

I’d say this is expected, as camera.position changes when you move the camera, so the ray origin changes accordingly. If you don’t want this behavior, you should indeed clone the position.

But it doesn’t seem like it’s drawing the rays at all if not cloned. When cloned and working correctly (like in the picutre), as I move the camera about, I can see rays being drawn from previous positions. I am calling the method in the beforeRender method, so it should use the updated the position but I don’t see anything. Any ideas on why that may be the case?

btw, thank you for the fast response

You will see in this PG that the lines are drawn but not visible by the main camera because they follow it:

The second camera (on the right) is fixed and is looking at the scene from a distance, so that we can see the lines.

If you clone the position, you will see that the lines don’t move with the camera, they stay fixed.

1 Like

Unfortunately I can’t see the PG link - but with a night of sleep and your explanation I see what the problem was. I had assumed the rays drawn were static (cloning not only means rays don’t share the same position as the current camera but area also independent of each other) and that the camera position was set to a new point rather than modified in place; my past experience with C#'s structs being passed by value is something I need to adjust to. Sorry for the inconvenience on such a silly issue, and Thank you so much for your help.

I’m not sure why the PG does not work for you, the link does work for me… Do you have an error in the console log?

Yes, I was getting a 404.

I was curious about how the url structure worked for the playground so I created a few revisions after commenting. I am assuming that this is what’s being shown since the code is identical to the first revision and doesn’t contain the updates that I believe you made, like a second camera.

I have created a new revision:

1 Like

Oh that’s really cool, thanks!