Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon


15. November 2016

 

Welcome to the getting started tutorial in the ongoing BabylonJS Tutorial Series.  Today we are going to look at creating our first simple Babylon application setup and running.  As always there is a HD video version of this tutorial available here or embedded down below. 

 

To get started with BabylonJS, we need a web page containing a <CANVAS> tag to host our application.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        #canvas {
            width:100%;
            height:100%;
        }
    </style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>

 

Nothing special here.  We simply create a canvas tag named canvas, style it so it takes up the entire page and that’s about it.  Now we need to link to the BabylonJs library.  You’ve got a few options here, you can download it locally or host it from a content delivery network (CDN).  I’ll take this approach, as it’s generally the fastest option for end users.  You can even create a stripped down version with only the required features here.

 

The options for using BabylonJS include:

 

Babylon.max.js is the most human readable of the versions, making it the easiest to debug but the slowest to load.  During development, this is the version I am going to use.  Simply link to this library somewhere within the <HEAD> tag of our HTML.

<script src="http://cdn.babylonjs.com/2-4/babylon.max.js"></script>

 

We have our host webpage setup and Babylon linked, time to finally get down to some code.  Below our canvas, add the following code:

    <script>
        window.addEventListener('DOMContentLoaded', function(){
            var canvas = document.getElementById('canvas');

            var engine = new BABYLON.Engine(canvas, true);
            var createScene = function(){
                var scene = new BABYLON.Scene(engine);
                
                scene.clearColor = new BABYLON.Color3.White();
                var camera = new BABYLON.FreeCamera('camera1', new BABYLON.
                Vector3(0, 0,-10), scene);
                camera.setTarget(BABYLON.Vector3.Zero());

                var box = BABYLON.Mesh.CreateBox("Box",4.0,scene);
                
                return scene;
            }

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

        });
    </script>

 

When we run this code we should see:

image

 

Humble beginnings certainly, but our first running app is complete.  So what are we seeing here?  It’s an unlit cube viewed by a camera looking at the origin from –10 units down the z-axis.  Let’s take a quicker look at the code that got us here.  First we create a function that we call on DOMContentLoaded event fired, so basically when our page is loaded, this function is called.  Let’s walk through the function.

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

This code gets a reference to the canvas tag we created in our HTML file.  We then use this canvas to create an instance of our Babylon game engine.

var createScene = function(){
    var scene = new BABYLON.Scene(engine);
    scene.clearColor = new BABYLON.Color3.White();
    var camera = new BABYLON.FreeCamera('camera1', new BABYLON.Vector3(0, 0,-10),
    scene);
    camera.setTarget(BABYLON.Vector3.Zero());
    var box = BABYLON.Mesh.CreateBox("Box",4.0,scene);
    return scene;
}

Here we are creating a function that will setup our scene.  First we create a new Scene using our newly created engine.  We then set the clear color to white.  The clear color is the color that each frame is cleared with between calls, essentially setting the background color to white.  Next we create a FreeCamera named “camera1”, located at –10 along the Z axis in our scene.  Next we set the target to the origin (0,0,0).  We will go into more detail on cameras shortly, so let’s skip over this for now. Then we create a cube at the origin named “Box” that is 4x4x4 in dimensions.  Notice in both when we create the Camera and Box we pass the scene in.  This causes these entities to be created in that particular scene.  Finally we return our newly created scene from our function.

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

 

Next we create our scene by calling our just defined createScene() function.  We then start our game loop calling engine.runRenderLoop().  The game loop can be thought of as the heart of our game.  This is a loop that will be called over and over as fast as possible.  If for example your game is drawing at 60FPS, this function is called 60 times in a second.  For now all we do is call scene’s render() method, which causes the contents of that scene to be drawn.

 

Here now is the code in it’s entirety.  ( A WebStorm project is available in the GFS Patreon Dropbox directory Tutorial Series –> Babylon for backers )

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://cdn.babylonjs.com/2-4/babylon.max.js"></script>

    <style>
        #canvas {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script>
        window.addEventListener('DOMContentLoaded', function () {
            var canvas = document.getElementById('canvas');
            var engine = new BABYLON.Engine(canvas, true);
            var createScene = function () {
                var scene = new BABYLON.Scene(engine);
                scene.clearColor = new BABYLON.Color3.White();
                var camera = new BABYLON.FreeCamera('camera1', new BABYLON.
                Vector3(0, 0, -10), scene);
                camera.setTarget(BABYLON.Vector3.Zero());
                var box = BABYLON.Mesh.CreateBox("Box", 4.0, scene);
                return scene;
            }
    
            var scene = createScene();
            engine.runRenderLoop(function () {
                scene.render();
            });
        });
    </script>
</body>
</html>

 

That’s it for now.  In the next part we will explore cameras in more detail.

 

The Video

GameDev News , , ,

blog comments powered by Disqus

Month List

Popular Comments

Unity Release Patch 5.3.5p1
Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon


25. May 2016

 

This week brings another Unity patch, this time 5.3.5P1.  This release is primarily composed of fixes with some minor Windows Store functionality improvements and better stack reporting on crash.  The patch is available here.

 

Patch Release Notes:

 

Improvements
  • Runtime: During crashes even if the stack walking is aborted with error (RtlLookupFunctionEntry returned NULL function. Aborting stack walk), Unity will display stripped stack trace instead of displaying zero stack frames.
  • (791792) - Windows Store: Expanded UnityEngine.WSA.Cursor.SetCustomCursor, if you pass 0 to this function, it will restore the cursor to arror icon.
  • (792507) - Windows Store: Improved 'NULL != certificate' errors, it will now provide a human readable message why it failed to create a certificate.
Fixes
  • (778825) - 2D: Generate sprite mesh correctly for sprite with outline data after changing texture's max size setting.
  • (770093) - Android: Pause choreographer when activity is paused to fix CPU usage of Unity apps when the app is in background.
  • (790261) - Animation: Fix for animation stopping before reaching designated position.
  • (780289) - AssetBundle: Fixed the issue that failed to asynchronously load the object with script that had the same name as other assets in a bundle.
  • (780836, 761626) - AssetBundles: Fixed intermittent crash due to thread-safety issues.
  • (784401) - Editor: Fixed: No auto license updates since Unity 5.1.
  • (784822, 794090, 759483) - Graphics: Fixed some cases of incorrectly "Releasing Render Texture that is set as Camera.targetTexture", resulting in losing Camera.targetTexture - e.g. in case of device resume after sleep on iOS/Android, context-loss on DirectX or changing Emulation Layer in the Editor.
  • (787701) - IL2CPP: Load the stack value as unsigned for the conv.r.un opcode in IL.
  • (789160) - iOS/IL2CPP: Corrected managed stack traces which could have one incorrect frame when a NullReferenceException occurred.
  • (792606) - iOS: Fixed a crash when releasing WebRequest components.
  • (788483) - Samsung TV: UnityEngine.Ping has been fixed and will no longer report permissions issues.
  • (784481) - Scripting: Avoid allocating GC memory during Coroutine iteration.
  • (none) - Substance: Avoid re-generating ProceduralMaterials twice when switching color space.
  • (780071) - Substance: Fxed "Mismatched LayoutGroup.Repaint" error message appearing in console when assigning a ProceduralMaterial to a mesh.
  • (776052) - Substance: Fixed baked ProceduralTextures being serialized without their baked data.
  • (779560) - Substance: Fixed a crash in VisibleIf expression evaluation caused by looking up an input by label instead of by identifier.
  • (781118) - Substance: Fixed a crash when undoing a modification of the shader assigned to a ProceduralMaterial .
  • (762285) - Substance: Fixed GetProceduralXYZ returning 0 when used with an input's label instead of its identifier.
  • (none) - Substance: Fixed normal maps textures being incorrectly processed when used as image inputs to a ProceduralMaterial.
  • (779574) - Substance: Fixed ProceduralMaterials being stuck in "Generating..." state when leaving playmode as they are being computed.
  • (795563) - Substance: frozen ProceduralMaterials can now be cloned. Procedural properties of a cloned frozen ProceduralMaterial cannot be changed anymore, but regular material properties can.
  • (none) - Substance: ProceduralTextures being cached to disk/flash now have their size correctly taken into account when querying Caching.spaceOccupied.
  • (776803) - Substance: Speed up the processing of BakeAndDiscard materials when loading scenes.
  • (none) - Substance: Now warn the user when an input of a BakeAndDiscard ProceduralMaterial is being set at runtime.
  • (774423) - UI: Fixed occasional crashes when modifying elements of non-Overlay Canvases.
  • (790264) - UI: Fixed World canvas not rendering in editor game view.
  • (507878) - Windows Standalone: Launcher will correctly display unicode symbols for input bindings.
  • (none) - Windows Store: Added command line argument -dontConnectAcceleratorEvent, which could help to solve issues with XAML controls used together with Unity.
  • (790408) - Windows Store: Do not overwrite solution file when building on top.
  • (778842) - Windows Store: Fixed DisconnectedException while pluging/unplugin joystick from usb multiple times.
  • (792589) - Windows Store: Fixed an issue where user couldn't enter @ symbol with touch screen keyboard when spanish language is selected.
  • (790319) - Windows Store: Fixed an issue with generics, causing access reduction exception at runtime.
  • (792618) - Windows Store: Fixed Screen.orientation sometimes reporting incorrect value on startup.
  • (786277) - Windows Store: NetworkTransport.ConnectEndPoint will work correctly on UWP (required by secure sockets), note this function will not work on older Windows Store SDKs.
  • (790537) - Windows Store: Workaround a driver bug in Lumia 950, the screen was flickering when navigation bar was spawning or despawning. Basically we replace ID3D11DeviceContext::ClearDepthStencilView (which corrupts stencil buffer somehow) with a full screen quad draw call which clears depth/stencil.

GameDev News

blog comments powered by Disqus

Month List

Popular Comments