Playground question

I’m looking at this playground, multipick | Babylon.js Playground (

Does anyone know what these code are doing?

function vecToLocal(vector, mesh){
var m = mesh.getWorldMatrix();
var v = BABYLON.Vector3.TransformCoordinates(vector, m);
return v;

var forward = new BABYLON.Vector3(0,0,1);
forward = vecToLocal(forward, box);
var direction = forward.subtract(origin);
direction = BABYLON.Vector3.Normalize(direction);

1 Like

VecToLocal takes a world vector and applies any rotation and scaling of the mesh to the vector, ie it places it in the frame of reference of the mesh local axes.

The forward part takes the initial forward direction of the mesh as (0, 0, 1) and calculates the forward direction of the mesh after rotation.

1 Like

I still do not really understand :sweat_smile: can you explain more about what this means: applies any rotation and scaling of the mesh to the vector? And also why need to subtract and normalize?

@pigga, in this demo we want to cast a ray in the forward direction relative to the mesh. As the mesh rotates the forward vector will no long be Vector3(0,0,1) but it will depend on the mesh`s rotation. What vecToLocal is doing is taking into consideration the mesh’s transform to find Vector(0, 0, 1) relative to that.

However, the TransformCoordinates will apply all mesh transformations (rotation, translation and scaling) to the forward vector and in this case we only want it to be corrected by rotation. In order to remove the translation contribution we have to subtract the mesh position (which in this case is the origin position itself). We don’t have to do anything for removing scale because that will be taken care by normalizing the vector.

Finally, In order to cast a ray in the scene o need the ray origin and direction, direction vectors usually are normalized since we only care about the direction they are pointing to and that should not change with different magnitudes (vector (1, 0, 0) points in the same direction as vector (2, 0, 0)).


Hello @pigga just checking in, do you have any further questions? :slight_smile:

If you want to look more into this topic, this is usually called “object picking”, and there are many interesting techniques and optimizations that can go into it. Here are some resources:
Mesh Picking | Babylon.js Documentation (
Picking · 3DCollisions (
Mouse Picking with Ray Casting - Anton’s OpenGL 4 Tutorials (

1 Like