Scene.pointer to Vector3

For the project that i am working on i need to be able to click the canvas and spawn a mesh on that point.
I tried using the scene.pointerY / scene.pointerX, however i’m not be able to convert this to a valid babylon Vector 3 point.

Does anybody know a solution for this?
Thanks in regards.

Hi @Snekmel and welcome to the forum

In order to spawn a mesh in the scene at a 3D position, you first have to convert the 2D coordinates (scene.pointer) to 3D. This can be done with a raycast where the ray hits a plane and the hit point becomes the spawning position.
If you don’t have a plane to do the raycasting, you can call

var pickResult = scene.pick(scene.pointerX, scene.pointerY);

and the ray corresponding to the mouse pointer is:

pickResult.ray.origin 
pickResult.ray.direction

then you have to choose an arbitrary distance between the origin and your destination so you can compute a 3D position:

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

Some documentation here : Raycasts - Babylon.js Documentation

Hi @Cedric,

I am into the very same issue and your answer seems interesting. Could you give more details about your end position formula ? Do you mean :

position.x = pickResult.ray.origin.x + pickResult.ray.direction.x * distance
position.y = pickResult.ray.origin.y + pickResult.ray.direction.y * distance
position.z = pickResult.ray.origin.z + pickResult.ray.direction.z * distance

It doesn’t really work for me…

Sure! Do you have a PG ?

Thanks @Cedric ! The problem was elsewhere now it works !

1 Like

There’s a method for this

let ray = scene.createPickingRay(scene.pointerX, scene.pointerY, BABYLON.Matrix.Identity(), null);
let hit = scene.pickWithRay(ray);
let pickedPoint = hit.pickedPoint;