Creating a custom mesh in BabylonJS


A playground is available with the Quad creation code:

The process of creating a custom mesh in Babylon is very similar to Unity:

  • Create an array of floats to determine vertex position. Our graphics processor will interpret a series of 3 float values as the definition of a point in 3D space.
  • Create an array of integers to create indices to render our triangles. Rendered geometry is actually (usually) made of triangles so we’ll need to define a series of 3 indices to define the 3 points of the triangle to be rendered. The indices are the indices to the vertex array defined previously.
  • Set those positions and indices to our mesh object.

Now there is one problem that we need to be aware of. By default objects have their backface culled. That means that IF the object is pointing away from the camera, it won’t be rendered. For example if the backface of our mesh is facing the camera, it will be culled.

This is important to know because when generating a mesh, the order in which you provide the indices will define the front face so, if you think you haven’t made any mistake in your code and some parts (or the whole thing) are not being rendered, check the order of the indices and set them correctly. The correct order depends on the engine so it might be easier to just try out clockwise/counter-clockwise and see which works (Babylon seems to be using counterclockwise and so does Blender, while Unity uses clockwise ordering).

Anyway, here is the code for the Quad creation:

    var quad = new BABYLON.Mesh("quad", scene);
    var positions = [0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0];
    var indices = [0, 1, 2, 1, 3, 2];
    var vertexData = new BABYLON.VertexData();

    vertexData.positions = positions;
    vertexData.indices = indices;