Introduction

Recently, I have been experimenting with writing 3D games, mainly for mobile Virtual Reality. Today I thought I might want to have a go at writing a desktop 3D game, and played with Electron, Node.js and BabylonJS so I can write my code in JavaScript and use HTML5 to develop my own cross-platform 3D game engine.

The Tools

  • Electron, a tool for building cross-platform desktop applications in JavaScript, HTML5 and CSS. Essentially, this is a WebKit module for Node.js.
  • BabylonJS, a JavaScript framework for building 3D games in HTML5, with WebGL.

Setup

Below is a set of steps to follow to write your first cross-platform Desktop 3D Application using Electron, Node.js and BabylonJS, running on Linux, macOS and Windows:

1. Install Node.js

https://nodejs.org/en/download/

2. Install Electron

npm install -g electron

3. Clone the Quick-Start Application

https://github.com/electron/electron-quick-start

Create Your First 3D World

Add the following code to your quick-start application's index.html (based on http://www.babylonjs-playground.com/):

var canvas = document.getElementById("renderCanvas");

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

var createScene = function () {
    // This creates a basic Babylon Scene object (non-mesh)
    var scene = new BABYLON.Scene(engine);

    // This creates and positions a free camera (non-mesh)
    var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);

    // This targets the camera to scene origin
    camera.setTarget(BABYLON.Vector3.Zero());

    // This attaches the camera to the canvas
    camera.attachControl(canvas, true);

    // This creates a light, aiming 0,1,0, to the sky (non-mesh)
    var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);

    // Default intensity is 1. Let's dim the light a small amount
    light.intensity = 0.7;

    // Our built-in 'sphere' shape. Params: name, subdivs, size, scene
    var sphere = BABYLON.Mesh.CreateSphere("sphere1", 16, 2, scene);

    // Move the sphere upward 1/2 its height
    sphere.position.y = 1;

    // Our built-in 'ground' shape. Params: name, width, depth, subdivs, scene
    var ground = BABYLON.Mesh.CreateGround("ground1", 6, 6, 2, scene);

    return scene;
};

var scene = createScene();

engine.runRenderLoop(function () { scene.render(); });