Babylon.JS Multi-material Tutorial

Learn WebGL and Babylon.js at your own pace

Feel free to check out our online course 3D Programming with WebGL and Babylon.js for Beginners on Zenva Academy. The course covers the Babylon.js framework and explains all you need to get started with using this fantastic library in new or existing projects.

Tutorial

A multi-material is used to apply different materials to different parts of the same object as you can see in this screen capture (from www.babylonjs.com):

image

To be able to define a multi-materials you first have to define some standard materials:

Then you can create a multi-material in order to gather them all:

You are now able to affect the multi-material to your mesh:

But if you do that, you will see that the sphere will only use the first submaterial (the red bumped one). This is because by default a mesh is is designed to use only one material.

You can specify which part of the mesh uses a specific material by using the subMeshes property. By default, every mesh comes with only one submesh that cover the entire mesh.

To define multiple submeshes, you just have to use this code:

In this case, we will have 3 parts:

  • One starting from index 0 to index 900
  • One starting from index 900 to index 1800
  • One starting from index 1800 to index 3880

A submesh is defined with:

  • The index of the material to use (this index is used to find the correct material Inside the subMaterials collection of a multi-material)
  • The index of the first vertex and the count of vertices used (To optimize things for collisions for instance)
  • Index of the first indice to use and indices count
  • The parent mesh

So with the code below, we can use the first material on the top part of the sphere, the second material on the middle part and the last material on the bottom part of the sphere.

Published by

David Catuhe

David Catuhe is technical evangelist lead at Microsoft France. He defines himself as a geek. He loves to develop with JavaScript and HTML5 but also with DirectX, C#, C++ or even Kinect (He wrote a book about it which is available on Amazon).David has a blog called Eternal Coding where he writes about HTML5, Windows, Kinect and 3D Development.

Share this article