Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1036914 of Building up a basic demo with Babylon.js

  • Revision slug: Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Babylon.js
  • Revision title: Building up a basic demo with Babylon.js
  • Revision id: 1036914
  • Created:
  • Creator: PushpitaPikuDey
  • Is current revision? No
  • Comment

Revision Content

Babylon.js is one of the most popular 3D game engines used by the developers. As any other 3D library, it provides built-in functions to help you implement common 3D functionality more quickly. In this article we'll take you through the real basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML and writing the JavaScript code.

We will try to put a simple demo first — a cube rendered on the screen. If you have already worked through our Building up a basic demo series with Three.js, PlayCanvas or A-Frame (or you are familiar with other 3D libraries) you'll notice that Babylon.js works on similar concepts: camera, light and objects.

Environment setup

To start developing with Babylon.js, you don't need much. You should start off by:

  • Making sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome.
  • Creating a directory to store your experiments in.
  • Saving a copy of the latest Babylon.js engine inside your directory.
  • Opening the Babylon.js documentation in a separate tab — it is useful to refer to.

HTML structure

Here's the HTML structure to be used: 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>MDN Games: Babylon.js demo</title>
    <style>
        html,body,canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; }
    </style>
</head>
<body>
<script src="babylon.js"></script>
<canvas id="render-canvas"></canvas>
<script>
    var canvas = document.getElementById("render-canvas");
    /* all our JavaScript code goes here */
</script>
</body>
</html>

It contains some basic information like the document {{htmlelement("title")}}, and some CSS to set the width and height of the {{htmlelement("canvas")}} element that Babylon.js will use to fill the entire available viewport space. The first {{htmlelement("script")}} element includes the Babylon.js library in the page; we will write our example code in the second one. There is one helper variable already included, which will store a reference to the <canvas> element.

Before reading on, copy this code to a new text file and save it in your working directory as index.html.

Babylon.js engine

We have to create the Babylon.js engine first (using the given <canvas> element),before we start developing our game. Add the following code to the bottom of your second <script> element:

var engine = new BABYLON.Engine(canvas);

The BABYLON global object contains all the Babylon.js functions available in the engine.

Scene

A scene is the place where everything happens. While creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen. Let's create it by adding the following lines just below our previous code:

var scene = new BABYLON.Scene(engine);
scene.clearColor = new BABYLON.Color3(0.8, 0.8, 0.8);

Thus, the scene is created and the second line is setting the background color to light gray. To make the scene actually visible we have to render it.

Render loop

Add those lines at the end of the <script> tag, just before the closing </script>.

var renderLoop = function () {
    scene.render();
};
engine.runRenderLoop(renderLoop);

We're using engine's runRenderLoop method to execute the renderLoop function and actually, to render a scene on every frame and the loop will continue to render indefinitely.

Camera

Now, when the setup code is in place we need to think about implementing the standard scene components: camera, light and objects. Let's start with the camera — add this line to your code below the scene creation and the line where we defined the clearColor.

var camera = new BABYLON.FreeCamera("camera", new BABYLON.Vector3(0, 0, -10), scene);

There are many cameras available in Babylon.js and FreeCamera is the most basic and universal one. To initialize it you need to pass three parameters: any name you want to use for it, the coordinates in the 3D space and the scene you want to add it to.

Note: You probably noticed BABYLON.Vector3 method - it's a way the engine is defining a 3D position on the scene. Babylon.js is bundled with a complete math library for handling vectors, colors, matrix etc.

Light

There are various types of light sources available in Babylon.js; the most basic one is the PointLight, which works like a flashlight — shinig a spotlight in a given direction. Add the following below defines your camera: 

var light = new BABYLON.PointLight("light", new BABYLON.Vector3(10, 10, 0), scene);

The parameters are very similar to the previously defined camera: the name of the light, a new position in 3D space and the scene to which the light is added.

Geometry

Now the scene is properly rendering we can start adding 3D shapes to it. To speed up development Babylon.js provides a bunch of predefined primitives that you can use to create shapes instantly in a single line of code. There are cubes, spheres, cylinders and more complicated shapes available. Drawing everything for given shape is taken care of by the engine, so we can focus on the high level coding. Let's start by defining the geometry for a box shape — add the following new code below your previous additions:

var box = BABYLON.Mesh.CreateBox("box", 2, scene);

A mesh is a way the engine creates the geometry shapes, so the material can be easily applied to them later on. In this case we're creating a box using the Mesh.CreateBox method with it's own name, size 2, added to the scene.

Note: The size or position values (e.g. for the box size) are unitless, and can basically be anything you deem suitable for your scene — milimeters, meters, feet, or miles — it's up to you.

If you save and refresh now, your object will look like a square, because it's facing the camera. The good thing about objects is that we can move them on the scene however we want, for example rotating and scaling as we like. Let's apply a little bit of rotation to the box, so we can see more than one face — again, add below the previous one:

box.rotation.x = -0.2;
box.rotation.y = -0.4;

The box look black though - it's because we haven't defined any material for it yet.

Material

Material is that thing covering the object — the colors or texture on its surface. In our case we will use a simple blue color to paint our box. There are many types of ">materials that can be used, but for now the standard one should be enough for us. Add this lines below the previous ones:

var boxMaterial = new BABYLON.StandardMaterial("material", scene);
boxMaterial.emissiveColor = new BABYLON.Color3(0, 0.58, 0.86);
box.material = boxMaterial;

The StandardMaterial takes two parameters: a name and the scene. The second line is defining an emissiveColor - the one that will be visible for us. We can use the built-in Color3 function to define it. The last, third line is assigning the newly created material to our box.

Congratulations, you've created your first object in a 3D environment using Babylon.js! It was easier than you thought, right? Here's how it should look:

Blue Babylon.js 3D box on the gray background.

And here's the code we have created so far:

{{JSFiddleEmbed("https://jsfiddle.net/end3r/9zoeo5sy/","","350")}}

You can also check it out on GitHub.

More shapes

We have a box on the scene already; now let's try adding more shapes.

Torus

Let's try adding a torus — add the following lines below the previous code:

var torus = BABYLON.Mesh.CreateTorus("torus", 2, 0.5, 15, scene);
torus.position.x = -5;
torus.rotation.x = 1.5;

It will create a torus and add it to the scene, the parameters are: name, diameter, thickness, tessellation (number of segments) and the scene. We also position it a bit to the left and rotate on the x axis to see it better. Now let's add a material:

var torusMaterial = new BABYLON.StandardMaterial("material", scene);
torusMaterial.emissiveColor = new BABYLON.Color3(0.4, 0.4, 0.4);
torus.material = torusMaterial;

It looks similar to the box element - we're creating the standard material, give it a grayish color and assign it to the torus.

Cylinder

Creating a cylinder and its material is done in almost exacly the same way as we did for the torus. Add the following code, again, at the bottom of your script:

var cylinder = BABYLON.Mesh.CreateCylinder("cylinder", 2, 2, 2, 12, 1, scene);
cylinder.position.x = 5;
cylinder.rotation.x = -0.2;
var cylinderMaterial = new BABYLON.StandardMaterial("material", scene);
cylinderMaterial.emissiveColor = new BABYLON.Color3(1, 0.58, 0);
cylinder.material = cylinderMaterial;

The cylinder parameters are: name, height, diameter at the top, diameter at the bottom, tessellation, height subdivisions and the scene. It is then positioned on the right and rotated a bit to see its 3D shape. Then the yellow colored material is added.

Here's how it should look right now:

Light gray torus, blue box and yellow cylinder created with Babylon.js on the gray background.

This works, but it is a bit boring. In a game something is usually happening — we can see animations and such — so let's try to breathe a little life into those shapes by animating them.

Animation

We already used position or rotation to adjust the position of the shapes; we could also scale them. To show actual animation, we need to make changes to these values inside the rendering loop at the end of our code, so they are updated on every frame. Add the helper t variable that we will use for animations:

var t = 0;
var renderLoop = function () {
    scene.render();
    t -= 0.01;
    // animation code goes here
};
engine.runRenderLoop(renderLoop);

The t variable will be incremented on every rendered frame.

Rotation

Applying rotation is as easy as adding this line at the end of the renderLoop function:

box.rotation.y = t*2;

It will rotate the box along the y axis.

Scaling

Add this line below the previous one to scale the torus:

torus.scaling.z = Math.abs(Math.sin(t*2))+0.5;

There's a little bit of adjustments made to make the animation look and feel nice. You can experiment with the values and see how it affects the animation.

Moving

By changing the position of the cylinder directly we can move it on the scene - add this line below the previous one:

cylinder.position.y = Math.sin(t*3);

The cylinder will float in the air up and down on the y axis thanks to the Math.sin function.

Conclusion

Here's the final code listing, along with a viewable live example:

{{JSFiddleEmbed("https://jsfiddle.net/end3r/8r66fdvp/","","350")}}

You can also see it on GitHub and fork the repository if you want to play with it yourself locally. Now you know the basics of Babylon.js engine; happy experimentation!

See also

Revision Source

<p class="summary"><span class="seosummary"><a href="https://babylonjs.com/">Babylon.js</a> is one of the most popular 3D game engines used by the developers. As any other 3D library, it provides built-in functions to help you implement common 3D functionality more quickly. In this article we'll take you through the real basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML and writing the JavaScript code.</span></p>

<p>We will try to put&nbsp;a simple demo first — a cube rendered on the screen. If you have already worked through our <em>Building up a basic demo</em> <a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web">series</a> with <a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Three.js">Three.js</a>, <a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas">PlayCanvas</a> or <a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_A-Frame">A-Frame</a> (or you are familiar with other 3D libraries) you'll notice that Babylon.js works on similar concepts: camera, light and objects.</p>

<h2 id="Environment_setup">Environment setup</h2>

<p>To start developing with Babylon.js, you don't need much. You should start off by:</p>

<ul>
 <li>Making sure you are using a modern browser with good <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API">WebGL</a> support, such as the latest Firefox or Chrome.</li>
 <li>Creating a directory to store your experiments in.</li>
 <li>Saving a copy of the <a href="https://cdn.babylonjs.com/2-3/babylon.js">latest Babylon.js engine</a> inside your directory.</li>
 <li>Opening the <a href="https://doc.babylonjs.com/">Babylon.js documentation</a> in a separate tab — it is useful to refer to.</li>
</ul>

<h2 id="HTML_structure">HTML structure</h2>

<p>Here's the HTML structure to be used:&nbsp;</p>

<pre class="brush: html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;MDN Games: Babylon.js demo&lt;/title&gt;
    &lt;style&gt;
        html,body,canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;script src="babylon.js"&gt;&lt;/script&gt;
&lt;canvas id="render-canvas"&gt;&lt;/canvas&gt;
&lt;script&gt;
    var canvas = document.getElementById("render-canvas");
    /* all our JavaScript code goes here */
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>

<p>It contains some basic information like the document {{htmlelement("title")}}, and some CSS to set the width and height of the {{htmlelement("canvas")}} element that Babylon.js will use to fill the entire available viewport space. The first {{htmlelement("script")}} element includes the Babylon.js library in the page; we will write our example code in the second one. There is one helper variable already included, which will store a reference to the &lt;canvas&gt; element.</p>

<p>Before reading on, copy this code to a new text file and save it in your working directory as <code>index.html</code>.</p>

<h2 id="Babylon.js_engine">Babylon.js engine</h2>

<p>We have to create the Babylon.js engine first (using the given &lt;canvas&gt; element),before we start&nbsp;developing our game. Add the following code to the bottom of your second &lt;script&gt; element:</p>

<pre class="brush: js">
var engine = new BABYLON.Engine(canvas);
</pre>

<p>The <code>BABYLON</code> global object contains all the Babylon.js functions available in the engine.</p>

<h2 id="Scene">Scene</h2>

<p>A scene is the place where everything happens. While&nbsp;creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen. Let's create it by adding the following lines just below our previous code:</p>

<pre class="brush: js">
var scene = new BABYLON.Scene(engine);
scene.clearColor = new BABYLON.Color3(0.8, 0.8, 0.8);
</pre>

<p>Thus,&nbsp;the scene is created&nbsp;and the second line is setting the background color to light gray. To make&nbsp;the scene actually visible we have to render it.</p>

<h2 id="Render_loop">Render loop</h2>

<p>Add those lines at the end of the &lt;script&gt; tag, just before the closing &lt;/script&gt;.</p>

<pre class="brush: js">
var renderLoop = function () {
    scene.render();
};
engine.runRenderLoop(renderLoop);
</pre>

<p>We're using engine's <code>runRenderLoop</code> method to execute the <code>renderLoop</code> function and actually, to render a scene on every frame&nbsp;and the loop will continue to render indefinitely.</p>

<h2 id="Camera">Camera</h2>

<p>Now, when the setup code is in place we need to think about implementing the standard scene components: camera, light and objects. Let's start with the camera — add this line to your code below the scene creation and the line where we defined the <code>clearColor</code>.</p>

<pre class="brush: js">
var camera = new BABYLON.FreeCamera("camera", new BABYLON.Vector3(0, 0, -10), scene);
</pre>

<p>There are many <a href="https://doc.babylonjs.com/tutorials/Cameras">cameras</a> available in Babylon.js and <code>FreeCamera</code> is the most basic and universal one. To initialize it you need to&nbsp;pass three parameters: any name you want to use for it, the coordinates in the 3D space and the scene you want to add it to.</p>

<div class="note">
<p><strong>Note</strong>: You probably noticed <code>BABYLON.Vector3</code> method - it's a way the engine is defining a 3D position on the scene. Babylon.js is bundled with a complete math library for handling vectors, colors, matrix etc.</p>
</div>

<h2 id="Light">Light</h2>

<p>There are various types of <a href="https://doc.babylonjs.com/tutorials/Lights">light sources</a> available in Babylon.js; the most basic one is the <code>PointLight</code>, which works like a flashlight — shinig a spotlight in a given direction. Add the following below defines your camera:&nbsp;</p>

<pre class="brush: js">
var light = new BABYLON.PointLight("light", new BABYLON.Vector3(10, 10, 0), scene);
</pre>

<p>The parameters are very similar to the previously defined camera: the name of the light, a new position in 3D space and the scene to which the light is added.</p>

<h2 id="Geometry">Geometry</h2>

<p>Now the scene is properly rendering we can start adding 3D shapes to it. To speed up development Babylon.js provides a bunch of <a href="https://doc.babylonjs.com/tutorials/Discover_Basic_Elements">predefined primitives</a> that you can use to create shapes instantly in a single line of code. There are cubes, spheres, cylinders and more complicated shapes available. Drawing everything for given shape is taken care of by the engine, so we can focus on the high level coding. Let's start by defining the geometry for a box shape — add the following new code below your previous additions:</p>

<pre class="brush: js">
var box = BABYLON.Mesh.CreateBox("box", 2, scene);
</pre>

<p>A mesh is a way the engine creates the geometry shapes, so the material can be easily applied to them later on. In this case we're creating a box using the <code>Mesh.CreateBox</code> method with it's own name, size 2, added to the scene.</p>

<div class="note">
<p><strong>Note</strong>: The size or position values (e.g. for the box size) are unitless, and can basically be anything you deem suitable for your scene — milimeters, meters, feet, or miles — it's up to you.</p>
</div>

<p>If you save and refresh now, your object will look like a square, because it's facing the camera. The good thing about objects is that we can move them on the scene however we want, for example rotating and scaling as we like. Let's apply a little bit of rotation to the box, so we can see more than one face — again, add below the previous one:</p>

<pre class="brush: js">
box.rotation.x = -0.2;
box.rotation.y = -0.4;
</pre>

<p>The box look black though - it's because we haven't defined any material for it yet.</p>

<h2 id="Material">Material</h2>

<p>Material is that thing covering the object — the colors or texture on its surface. In our case we will use a simple blue color to paint our box. There are many types of <a doc.babylonjs.com="" href="&lt;a href=" http:="" materials="" tutorials="">"&gt;materials</a> that can be used, but for now the standard one should be enough for us. Add this lines below the previous ones:</p>

<pre class="brush: js">
var boxMaterial = new BABYLON.StandardMaterial("material", scene);
boxMaterial.emissiveColor = new BABYLON.Color3(0, 0.58, 0.86);
box.material = boxMaterial;
</pre>

<p>The <code>StandardMaterial</code> takes two parameters: a name and the scene. The second line is defining an <code>emissiveColor</code> - the one that will be visible for us. We can use the built-in <code>Color3</code> function to define it. The last, third line is assigning the newly created material to our box.</p>

<p>Congratulations, you've created your first object in a 3D environment using Babylon.js! It was easier than you thought, right? Here's how it should look:</p>

<p><img alt="Blue Babylon.js 3D box on the gray background." src="https://end3r.github.io/MDN-Games-3D/Babylon.js/img/cube.png" style="height:490px; width:600px" /></p>

<p>And here's the code we have created so far:</p>

<p>{{JSFiddleEmbed("https://jsfiddle.net/end3r/9zoeo5sy/","","350")}}</p>

<p>You can also <a href="https://github.com/end3r/MDN-Games-3D/blob/gh-pages/Babylon.js/cube.html">check it out on GitHub</a>.</p>

<h2 id="More_shapes">More shapes</h2>

<p>We have a box on the scene already; now let's try adding more shapes.</p>

<h3 id="Torus">Torus</h3>

<p>Let's try adding a torus — add the following lines below the previous code:</p>

<pre class="brush: js">
var torus = BABYLON.Mesh.CreateTorus("torus", 2, 0.5, 15, scene);
torus.position.x = -5;
torus.rotation.x = 1.5;
</pre>

<p>It will create a torus and add it to the scene, the parameters are: name, diameter, thickness, tessellation (number of segments) and the scene. We also position it a bit to the left and rotate on the <code>x</code> axis to see it better. Now let's add a material:</p>

<pre class="brush: js">
var torusMaterial = new BABYLON.StandardMaterial("material", scene);
torusMaterial.emissiveColor = new BABYLON.Color3(0.4, 0.4, 0.4);
torus.material = torusMaterial;
</pre>

<p>It looks similar to the box element - we're creating the standard material, give it a grayish color and assign it to the torus.</p>

<h3 id="Cylinder">Cylinder</h3>

<p>Creating a cylinder and its material is done in almost exacly the same way as we did for the torus. Add the following code, again, at the bottom of your script:</p>

<pre class="brush: js">
var cylinder = BABYLON.Mesh.CreateCylinder("cylinder", 2, 2, 2, 12, 1, scene);
cylinder.position.x = 5;
cylinder.rotation.x = -0.2;
var cylinderMaterial = new BABYLON.StandardMaterial("material", scene);
cylinderMaterial.emissiveColor = new BABYLON.Color3(1, 0.58, 0);
cylinder.material = cylinderMaterial;
</pre>

<p>The cylinder parameters are: name, height, diameter at the top, diameter at the bottom, tessellation, height subdivisions and the scene. It is then positioned on the right and rotated a bit to see its 3D shape. Then the yellow colored material is added.</p>

<p>Here's how it should look right now:</p>

<p><img alt="Light gray torus, blue box and yellow cylinder created with Babylon.js on the gray background." src="https://end3r.github.io/MDN-Games-3D/Babylon.js/img/shapes.png" style="height:210px; width:600px" /></p>

<p>This works, but it is a bit boring. In a game something is usually happening — we can see animations and such — so let's try to breathe a little life into those shapes by animating them.</p>

<h2 id="Animation">Animation</h2>

<p>We already used <code>position</code> or <code>rotation</code> to adjust the position of the shapes; we could also scale them. To show actual animation, we need to make changes to these values inside the rendering loop at the end of our code, so they are updated on every frame. Add the helper <code>t</code> variable that we will use for animations:</p>

<pre class="brush: js">
var t = 0;
var renderLoop = function () {
    scene.render();
    t -= 0.01;
    // animation code goes here
};
engine.runRenderLoop(renderLoop);
</pre>

<p>The <code>t</code> variable will be incremented on every rendered frame.</p>

<h3 id="Rotation">Rotation</h3>

<p>Applying rotation is as easy as adding this line at the end of the <code>renderLoop</code> function:</p>

<pre class="brush: js">
box.rotation.y = t*2;
</pre>

<p>It will rotate the box along the <code>y</code> axis.</p>

<h3 id="Scaling">Scaling</h3>

<p>Add this line below the previous one to scale the torus:</p>

<pre class="brush: js">
torus.scaling.z = Math.abs(Math.sin(t*2))+0.5;
</pre>

<p>There's a little bit of adjustments made to make the animation look and feel nice. You can experiment with the values and see how it affects the animation.</p>

<h3 id="Moving">Moving</h3>

<p>By changing the position of the cylinder directly we can move it on the scene - add this line below the previous one:</p>

<pre class="brush: js">
cylinder.position.y = Math.sin(t*3);
</pre>

<p>The cylinder will float in the air up and down on the <code>y</code> axis thanks to the <code>Math.sin</code> function.</p>

<h2 id="Conclusion">Conclusion</h2>

<p>Here's the final code listing, along with a viewable live example:</p>

<p>{{JSFiddleEmbed("https://jsfiddle.net/end3r/8r66fdvp/","","350")}}</p>

<p>You can also <a href="https://github.com/end3r/MDN-Games-3D/blob/gh-pages/Babylon.js/shapes.html">see it on GitHub</a> and <a href="https://github.com/end3r/MDN-Games-3D/">fork the repository</a> if you want to play with it yourself locally. Now you know the basics of Babylon.js engine; happy experimentation!</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="https://learningbabylonjs.com/">Learning Babylon.js book</a></li>
</ul>
Revert to this revision