Render games directly in your browser - BabylonJS

Babylon.js is a real-time 3D engine in the form of a JavaScript library for displaying 3D scenes in a web browser via HTML5. This 3D engine is interpreted natively by a web browser supporting the HTML5 standard.


6 min read

Babylon.js is a real-time 3D engine in the form of a JavaScript library for displaying 3D scenes in a web browser via HTML5.

This 3D engine is interpreted natively by a web browser supporting the HTML5 standard. The programming language used is JavaScript, allowing calculations and 3D rendering through the WebGL2 programming interface.

The Babylon.js source program is encoded in TypeScript. The version transposed into JavaScript is provided to the end-user so that he can use Javascript directly to access the Babylon.js API.

Version 4 offers a lot of new improvements

  • a visual scene inspector;
  • the use of independent modules that reduce the size of downloads;
  • an increase in performance (15% on average);
  • a more realistic rendering;
  • the support of the ammo.js physics engine as a plugin (including soft bodies management, among others);

The scene

The scene is not a visible object. It is an object that will contain all the others. It is the basis for everything! If we draw a parallel with cinema, the stage is the place where the actors will play their roles, where all the action will take place. It stops at what the camera sees, but the camera can go wherever it wants.

var createScene = function (engine) {
	...your code here
}

The graphics engine

While the scene will gather the elements, the graphics engine will have the job of rendering them into an image. This means that it will transform mathematical calculation flows into an image visible to the human eye, allowing you to explore the world you have created!

var engine = new BABYLON.Engine(canvas, true);

canvas being the divwhere the object is going to be rendered. In our case:

<canvas id="renderCanvas"></canvas>

You can get the canvas in your script like this:

window.addEventListener('DOMContentLoaded', function(){
            // get the canvas DOM element
            var canvas = document.getElementById('renderCanvas');

            // load the 3D engine
            var engine = new BABYLON.Engine(canvas, true);

}

Now that we have a scene and a graphics engine to calculate what's in it, we'll have to tell him what to look at! Just like in the movies, again, you need a camera to render an image on the screen. This one will have the same characteristics as traditional and physical cameras.

The camera & lights

Our scene is created, with a camera filming in the right place and a graphics engine ready to receive the first calculations to be made. But if we added an object now, we would only see black. We need light! The lights will help to illuminate the objects and create shadows to support the presence of the objects in the scene.

camera = new BABYLON.ArcRotateCamera("Camera", 33.7081, 0.9001, 39.91, BABYLON.Vector3.Zero(), scene);
    camera.setTarget(BABYLON.Vector3.Zero());
    camera.attachControl(canvas, false);

And the lights

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

var light1 = new BABYLON.HemisphericLight("hemi", new BABYLON.Vector3(0, 10, 0), scene);
light1.diffuseColor = new BABYLON.Color3(1, 1, 1);

The meshes (or objects)

Finally, the first visible elements! They are composed of a multitude of points defining a set of polygons that themselves form faces. Together, they produce an object that we call here mesh. This is what the user will see. Mountain, character, ocean, infinite space... everything that is an object displayed on the screen is a mesh.

Here we define a function that creates random cubes in a 100*100*100 box.
You'll see in a couple of seconds what it does.

// Create random cubes in a box of 100x100x100
function createCubesBall(num) {
    for (var i = 0; i < num; i++) {
        if (i === 0)
            cubes[i] = BABYLON.Mesh.CreateBox("b", 1.0, scene);
        else
            cubes[i] = cubes[0].createInstance("b" + i);

        var x = rnd(-50, 50);
        var y = rnd(-50, 50);
        var z = rnd(-50, 50);

        cubes[i].scaling = new BABYLON.Vector3(rnd(1.0, 1.5), rnd(1.0, 1.5), rnd(1.0, 10.0));

        cubes[i].position = new BABYLON.Vector3(x, y, z);

        cubes[i].lookAt(new BABYLON.Vector3(0, 0, 0));
    }
}

The result

With a few lines of code you can achieve great results.

This animation was created with this code in the footer

<script>
        window.addEventListener('DOMContentLoaded', function(){
            // get the canvas DOM element
            var canvas = document.getElementById('renderCanvas');

            // load the 3D engine
            var engine = new BABYLON.Engine(canvas, true);

            /*
	How to use lookat to make an eye-candy effect ! :)
	by Steve 'Stv' Duran for BabylonJS featured demos on 02.12.2015
*/
var camera;
var scene;

var cubes = [];
var cubes_mat;

// better random function
function rnd(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

// Create random cubes in a box of 100x100x100
function createCubesBall(num) {
    for (var i = 0; i < num; i++) {
        if (i === 0)
            cubes[i] = BABYLON.Mesh.CreateBox("b", 1.0, scene);
        else
            cubes[i] = cubes[0].createInstance("b" + i);

        var x = rnd(-50, 50);
        var y = rnd(-50, 50);
        var z = rnd(-50, 50);

        cubes[i].scaling = new BABYLON.Vector3(rnd(1.0, 1.5), rnd(1.0, 1.5), rnd(1.0, 10.0));

        cubes[i].position = new BABYLON.Vector3(x, y, z);

        cubes[i].lookAt(new BABYLON.Vector3(0, 0, 0));
    }
}

var createScene = function (engine) {
    scene = new BABYLON.Scene(engine);
    scene.clearColor = new BABYLON.Color3(0, 0, 0);

    camera = new BABYLON.ArcRotateCamera("Camera", 33.7081, 0.9001, 39.91, BABYLON.Vector3.Zero(), scene);
    camera.setTarget(BABYLON.Vector3.Zero());
    camera.attachControl(canvas, false);

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

    var light1 = new BABYLON.HemisphericLight("hemi", new BABYLON.Vector3(0, 10, 0), scene);
    light1.diffuseColor = new BABYLON.Color3(1, 1, 1);

    var sphere = BABYLON.Mesh.CreateSphere("s", 32, 5, scene);

    createCubesBall(1000);

    var mat_sphere = new BABYLON.StandardMaterial("s", scene);
    sphere.material = mat_sphere;

    var probe = new BABYLON.ReflectionProbe("probe", 512, scene);
    probe.renderList.push(sphere);

    cubes_mat = new BABYLON.StandardMaterial("m", scene);

    cubes[0].material = cubes_mat;

    var container = BABYLON.Mesh.CreateBox("cont", 110, scene);
    var mat_cont = new BABYLON.StandardMaterial("mc", scene);
    mat_cont.alpha = 0.1;
    container.material = mat_cont;

    var px = 0, py = 0, pz = 0;
    var cr = 0, cg = 0, cb = 0;
    var t = 0.0;

    scene.registerBeforeRender(function () {

        // sin/cos random direction
        px = 25.0 * Math.cos(t / 3.5);
        py = 25.0 + 10.0 * Math.sin(t / 4.0);
        pz = 25.0 * Math.cos(t / 4.5);

        // sin/cos random color between 0,1
        cr = 0.5 + 0.5 * Math.sin(t / 12);
        cg = 0.5 + 0.5 * Math.sin(t / 14);
        cb = 0.5 + 0.5 * Math.sin(t / 16);

        // Change sphere and cubes colors
        mat_sphere.diffuseColor = new BABYLON.Color3(cr, cg, cb);
        mat_sphere.emissiveColor = new BABYLON.Color3(cr, cg, cb);
        cubes_mat.diffuseColor = new BABYLON.Color3(cr, cg, cb);

        // Move our sphere
        sphere.position = new BABYLON.Vector3(px, py, pz);

        // Make all cubes look at the moving sphere
        for (var i = 0; i < cubes.length; i++) {
            cubes[i].lookAt(new BABYLON.Vector3(px, py, pz));
        }

        camera.alpha = 4.0 * (Math.PI / 20 + Math.cos(t / 30));
        camera.beta = 2.0 * (Math.PI / 20 + Math.sin(t / 50));
        camera.radius = 180 + (-50 + 50 * Math.sin(t / 10));

        t += 0.1;
    });

    return scene;
};

            // call the createScene function
            var scene = createScene();

            // run the render loop
            engine.runRenderLoop(function(){
                scene.render();
            });

            // the canvas/window resize event handler
            window.addEventListener('resize', function(){
                engine.resize();
            });
        });
    </script>

Then in the html of the bodywe inserted

<canvas id="renderCanvas"></canvas>

and in the headwe loaded all the required libraries

 <script src="https://cdn.babylonjs.com/babylon.js"></script>
    <style>

        #renderCanvas {
            width   : 100%;
            height  : 100%;
            touch-action: none;
        }
    </style>

Have fun !

BabylonJS 4.1

Welcome to Babylon.js 4.1 - Windows Developer Blog
Our mission is to create one of the most powerful, beautiful, and simple Web rendering engines in the world. Our passion is to make it completely open and free for everyone. Today, we are thrilled to announce the official release of Babylon.js 4.1! Before diving into more detail, we also want to hum…

Brave says no to error 404
Previous article

Brave says no to error 404

Brave has integrated the Internet Archive Wayback Machine directly into its browser to provide quick access to archived versions of web pages displaying a 404 error.

Find all URLs of a website in a few seconds - Python
Next article

Find all URLs of a website in a few seconds - Python

Have you ever wanted to extract all the URLs of a website quickly? We'll tell you how! It is hundreds of times faster than crawling all the pages of a website to find all of its URLs.


Related Articles

All you need to know about Corona
1 min read

GO TOP

🎉 You've successfully subscribed to Primates!
OK