API

Introduction To Coordinate Transformation

Transformations

Introduction to Coordinate Transformation

The first step in understanding coordinate transformation in Babylon.js is to understand how the data describing a mesh is stored. The positions of each vertex are kept in an array of coordinates in the local space of the mesh. Each transformation applied to the mesh is stored in a matrix called the World Matrix. For each rendered frame, the current World Matrix is used on the local space vertex data to obtain the world data for the mesh. Except in exceptional circumstances, such as baking a transformation or a user updating it, the mesh vertex data remains unchanged.

When you want one mesh, mesh_C, to be located in the frame of reference of another mesh, mesh_P, you can use coordinate transformation. Use the transformCoordinates function to apply the World Matrix of mesh_P to the required position.

For example, take mesh_P to be a box, a cube of size 1. In the local space of the box, the center of the top face is at (0, 0.5, 0). Move and rotate this box to a new position. We want mesh_C, a sphere, to be located at the center of the top face of the box in this new position. To do this, use

import { Vector3 } from "@babylonjs/core/Maths/math.vector";
const matrix = mesh_P.computeWorldMatrix(true); //true forces a recalculation rather than using cache version
const local_position = new Vector3(0, 0.5, ,0); //Required position of C in the local space of P
const global_position = Vector3.TransformCoordinates(local_position, matrix); //Obtain the required position of C in World Space
mesh_C.position = global_position;

Position sphere using TransformCoordinates: Position a Sphere Using Transform Coordinates

To translate the sphere by the direction vector (1, 1, 1), for example, you can add this to the current local position vector:

import { Vector3 } from "@babylonjs/core/Maths/math.vector";
const matrix = mesh_P.computeWorldMatrix(true);
const local_position = new Vector3(0, 0.5, 0);
local_position.addInPlace(new Vector3(1, 1, 1));
const global_position = Vector3.TransformCoordinates(local_position, matrix);
mesh_C.position = global_position;

Translate sphere using TransformCoordinates: Translate a Sphere Using Transform Coordinates

More extensive examples follow.