Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

29. November 2016

 

Welcome to the next part in the ongoing BabylonJS Tutorial Series.  In the previous tutorial we created our first simple scene which contained a simple camera.  In this tutorial we are going to explore the concept of camera’s in more depth.  As always there is an HD video version of this tutorial available here.

 

In the previous example we created a Free Camera.  A Free Camera is a camera that can be moved around using the mouse and keyboard.  Often of course you are going to want to be able to customize which keys are used to move the camera.  Here is an example that configured the camera to respond to the WASD keys.

 

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());
            camera.attachControl(canvas,true);
            camera.keysUp.push(87);    //W
            camera.keysDown.push(83)   //D
            camera.keysLeft.push(65);  //A
            camera.keysRight.push(68); //S


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

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

 

This code running:

1

When we create the camera, we pass it’s initial location within our scene.  In this case the position is (0,0,-10) or –10 down the Z axis.  Of course we also pass the scene the camera belongs to into the constructor as well.  Next we set the target of the camera, in this case the origin (or a Zero vector).  Finally we need the camera to actually receive input controls from the canvas.  This is simply done by calling attachControl.  This will result in input (such as mouse and keyboard) being passed to the camera for processing.  There is a member of the camera for keys representing up, down, left and right movement.  To each we pass the appropriate key scancode for the each key in the WASD combination.  When you run this code, you can now navigate around the scene using the WASD and free look using the mouse.

 

Another common camera type is a camera that orbits an object.  That is the camera revolves around the target in a circular orbit.  This is accomplished using an ArcRotateCamera.  Keep in mind however, you could also implement this camera in any other camera object available in Babylon, it would however be your responsibility to implement the functionality.  The follow is the code to create an ArcRotateCamera:

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

            var box = BABYLON.Mesh.CreateBox("Box",4.0,scene);
            var camera = new BABYLON.ArcRotateCamera("arcCam",
                    BABYLON.Tools.ToRadians(45),
                    BABYLON.Tools.ToRadians(45),
                    10.0,box.position,scene);
            camera.attachControl(canvas,true);

            return scene;
        }

 

This code running:

2

The three major parameters to the ArcRotateCamera are the alpha, beta and radius.  Radius is straight forward, this is the distance to orbit the target.  Think of the target as the mid point of a circle.  The radius then defines the size of the circle the camera will follow.  Alpha is the rotation angle around the X axis, while beta is the rotation angle around the Y axis.  Note that both take their parameter in radians instead of degrees, so we have to convert using the ToRadians() helper method.

 

The final kind of camera we are going to look at is the FollowCamera.  This camera does exactly what you’d expect, it follows a given target.  Let’s look at some code:

        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 box = BABYLON.Mesh.CreateBox("Box",4.0,scene);

            // Create a second object so we can actually witness the movement
            // Make this one wireframe to distiguish the difference.
            var box2 = BABYLON.Mesh.CreateBox("Box2",4.0,scene);
            var material = new BABYLON.StandardMaterial("material1",scene);
            material.wireframe = true;
            box2.material = material;

            box2.position = new BABYLON.Vector3(0,5,0);

            var camera = new BABYLON.FollowCamera("followCam",BABYLON.Vector3.
            Zero(),scene);
            camera.target = box;
            camera.radius = 100;
            camera.heightOffset = 0;
            camera.attachControl(canvas,true);

            scene.activeCamera = camera;
            return scene;
        }

        var scene = createScene();
        engine.runRenderLoop(function(){
            scene.getMeshByName("Box").position.y += 0.1;
            scene.getMeshByName("Box").position.x += 0.1;
            scene.render();
        });

 

This code running:

3

This code contains two rendered cubes, the second a box with a wireframe material attached.  This was done so you could actually detect movement!  We will cover the specifics of materials shortly so don’t sweat the details.  Notice in the creation of the FollowCamera we pass in a target to follow (box), how far away we should follow from (radius) and there is also a control for how height the camera should be relative to the target.

 

It should be noted these are only a few of the possible cameras implemented in BabylonJS.  There are a good dozen other cameras available out of the box with features like touch or gamepad control, VR rendering and more.  The basic principals remain the same regardless to camera type.

The Video

Programming , ,

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 , , ,

9. November 2016

BabylonBannerSplattered_thumb[3]

Welcome to the GameFromScratch.com tutorial series covering the BabylonJS HTML5 game engine.  The home page of the series is available here.  For each tutorial in the series there is both a text and video version available.  In this post we are simply going to introduce the BabylonJS engine, the scope of this tutorial series and discuss why you might want to use the Babylon engine and also some of the alternatives available should you decide not to.  If you’ve already decided on using the BabylonJS game engine, jump forward to the next tutorial.

 

BabylonJS Overview

I’m not going to go into a great deal of detail on the functionality included in BabylonJS as I have already featured this game engine in the Closer Look game engine series.  Instead we are going to take a quick top level look at the engine features.

 

Why Choose BabylonJS

So, why is the BabylonJS game engine a good choice for you?

  • Open source (Apache 2 license) and free to use
  • Full featured 3D game library (scene graph, physics, particles, models, sprites, etc)
  • Compatible with most modern WebGL browsers
  • Excellent tooling, including level editor, Unity exporter, model converters
  • Good documentation, samples and other learning materials

You can read the full feature set here.

 

Why Not Choose BabylonJS?

So we mentioned a number of Babylon’s strengths, but why would you *not* choose to use BabylonJS?  Well, beyond the fact you may not like how they implement things the biggest reason all comes down to your priorities.  WebGL performance isn’t on par with desktop OpenGL or even OpenGL ES, so there is a bit of a performance penalty at work here.  While HTML5 applications can be wrapped to run as applications on various mobile devices, again there is a price to be paid, in both performance and labor.

At the end of the day, personally, I think a lot of it comes down to your primary target.  If you are creating a browser game first and foremost, I recommend working in a browser native library such as BabylonJS.  This has the most direct workflow, is easiest to debug, etc.  If on the other hand the browser is just another target for you you are probably better off working in a game engine that also targets HTML5, such as Unreal or Unity.

 

Alternatives to BabylonJS

Shockingly there aren’t actually a ton of HTML5 3D game engines or frameworks like BabylonJS.  The most direct alternatives are:

 

By no means is that an exclusive list, but it does represent some of the most common 3D engines with WebGL as their primary target.

In addition to these engines several 3D engines offer HTML5 as a target including Unreal, Unity, Godot and many more.  The primary challenge with these options is the generated code is often illegible, acting almost identically to a compiled binary.  So if things don’t work right you are dependent on the engine developer to fix things.  Or if you wish to use a native browser feature, you are again dependent on the engine developers to support it in some form.

 

Enough overview, lets jump into the technical details.  I am aiming to keep each tutorial somewhat short and concise, both text and video versions.  Stay tuned for the first tutorial covering getting BabylonJS up and running.

 

The Video

Programming , , , ,

23. September 2016

 

Welcome back to our ongoing Godot tutorial series.  You may notice a pretty major change in the way Godot looks from previous tutorials.  This is because this tutorial jumps forward to Godot 2.1 which has an updated look and feel.  Don’t worry, the process is virtually identical regardless to which version of Godot you were running.  Today we are going to look at implementing 2D lights in your Godot game.  This will involve creating Godot light nodes, as well as occluders to prevent light.  We will also look at light masking, which is useful for implementing fog of war type effects. 

 

As always there is a video version of this tutorial available here.

 

First let’s set up a simple scene we can test our lighting on.  I simple create the following hierarchy using the default Godot icon sprite.

image

 

Then scale it up like so:

image

 

Now let’s add a Light2D as a Child to our Root node:

image

 

Notice the exclamation mark?

image

 

This is because we need to specify a texture to use as the light source.  I created the following image in Paint.net (process is shown in the video if you want to see how it was made):

LightMask

 

Notice that this image is a grayscale PNG file with an alpha channel.  Where there are no pixels at all, there will be no light shown.  Where it is whitest, the light will be most intense, while the darker it gets the less intense the light.  Save this image or create your own and add it to your project.  Now we set it as the texture source for our light.

image

 

Now if you move your Light2D node around the scene, you will see how it interacts with other objects in the scene:

GIF

 

There are a number of properties you can set for the light, such as the Energy (intensity) Color (tint) and Scale (size):

image

 

Notice also Mode.  We will come back to that in a minute.  Now sometimes you aren’t going to want all lights affecting all objects in the scene.  Thankfully there is a setting for that.  Notice in the range category there is a setting called Item Mask:

image

 

This controls what layer of items this light will interact with (there is also a setting for shadows as well).  Now if you switch over to your Sprite, under canvas item you will notice a Light Mask setting:

image

 

So long as the light and CanvasItem use the same masking channel, the light will apply to that node.  If they don’t use the same channel, the light will have no effect.  This can lower processing costs and enables you to exempt parts of your seen from being lit if so desired.

 

Now sometimes you want to have light actively blocked in your scene.  For example you might have a wall that should cast a shadow.  This is easy to implement in Godot using Occuluders.  This is simply a polygon area where the proverbial light don’t shine.  Let’s set one up around the nose of our Godot sprite.  Add a LightOccluder2D to your Sprite.

image

 

Your scene hierarchy should now look like:

image

 

With the LightOcculder2D node selected in the Scene the following icon should be available in the 2D view:

image

 

Click the pencil.  Now we want to draw our occlusion polygon, like so:

Gif2

 

Now notice the way the light interacts with the scene...

gif4

 

Now remember earlier on the Mode value of our Light2D node?

image

 

Now we are going to switch it over to “Mask” and show a powerful capability.  This can be used to create localized lights or to implement fog of war effects.  Just like before we need a texture to represent our light source, but this time we want the pixel values reversed, so I created the following image:

LightMask2

 

In this case the black area will receive no light, while the whitest area will contain the most light.  Here is the end result:

gif5

 

By scaling the light out to the full size of the screen, you can easily attach such a light to the character sprite to easily implement a fog of war type approach.

 

The Video

Programming ,

29. June 2016

 

Welcome to a new tutorial series here on GameFromScratch.com where we will be looking at core concepts of game programming.  This includes data structures, design patterns and algorithms commonly used in game development.  We start the series off with Finite State Machines.

 

There is an HD video version of this tutorial available here and embedded below.

 

What is a Finite State Machine?

 

A Finite State Machine (or FSM for short) is one of those concepts that sounds much scarier than it actually is.  In the simplest form it’s a datatype that can have only one value (state) from a finite selection of values(states).  The easiest way is to understand the finite state machine is to look at a real world example.

 

trafficLight

 

Yep, a traffic light is a perfect example of a FSM, or at least, the logic controlling it is.  Consider the three possible states this particular traffic light can be in.  At any given point (assuming I suppose the power is working...) the light will be one of three states, red, yellow or green.  It can never been more than one of those states at a time, it’s always red or yellow or green.  These are the two keep concepts of a finite state machine.  There are a finite number of states ( 3 in this case ) and only one is true or active at a time.

 

It’s a very simple concept, but extremely useful in game development.

 

What are FSMs Used For?

 

In game development, one of the most common uses for finite state machines is artificial intelligence.  Consider the example of PacMan’s ghosts.  A state machine can be used to control how they behave.  A ghost may have one of several different operating modes for example waiting to be released, hunting, hunted and dead.  The state machine is what is used to drive the ghost’s actions and to switch between states.  You will find AI examples absolutely loaded with state machines, often with some fuzzy logic controlling the transition between states to give a layer of unpredictability to your characters.

AI isn’t the only place of course, think of all the different things in a game that are related, there are multiple different states they can be in, but only one can be active at a time.  Game states are a very common example, where you break your game up into a series of states, for example Loading, Main Menu, Playing, High Score, Exiting.  Many game engines ( one such example is Phaser ) split your game up into a series of states.  The ultimate controller of these states is a finite state machine.  A sequential UI ( think of a sequence of dialogs controlled by next/back buttons ) can also be implemented using FSMs.  They are also commonly used to control elements in a games world.  Consider a game with a weather system, be it day or night cycles or season cycles like Spring, Summer, etc...  these would most likely be controlled via FSMs.

 

Implementing a Finite State Machine

 

The example we are going to use here is to implement a traffic light via FSM.  At it’s core the data is going to be stored in an enum, a natural fit for state machines, but stack based or array based options are also viable.  This example is not only going to switch the traffic lights periodically, it’s also going to implement callbacks so the world at large can interact with the light.  This example is implemented using C#, but should be easily adapted to most modern programming languages.

 

using System;

namespace GameFromScratchDemo
{

    public class TrafficLight{
        // This enum represents the three possible values our state machine can 
        be
        public enum States { Green, Yellow, Red };    
        // This is the amount of time for the timer to wait before changing 
        between states
        private const int LIGHT_DURATION = 5000;

        // An actual instance of our enum.
        private States _state;

        // The timer object that is going to be used to switch between states 
        private System.Threading.Timer _timer;

        // This function is called by the timer when it's time for a light to 
        change
        public void lightChanged(){
            System.Console.WriteLine("Light Changed");
            
            //  For each state, move to the next appropriate state.  I.e, red 
            becomes green, etc. 
            switch(_state){
                case States.Green:
                _state = States.Yellow;
                break;

                case States.Yellow:
                _state = States.Red;
                break;

                case States.Red:
                _state = States.Green;
                break;
            }

            // Reset our timer, so this will all happen again and again
            _timer.Change(LIGHT_DURATION,System.Threading.Timeout.Infinite);

            // Call our event.  This is used to communicate with the outside 
            world that our state change occured
            onStateChange(_state);
        }

        // In our constructor we simply set out default state (green) and 
        create/start our timer
        public TrafficLight() {
            _state = States.Green;
            System.Console.WriteLine("Light Created with initial Green state");

            _timer = new System.Threading.Timer( _ => lightChanged(), null, 
            LIGHT_DURATION,
                System.Threading.Timeout.Infinite);
        }

        // these two work together to provide the callback functionality
        // Implementing callback is going to differ greatly from langauge to 
        language
        public delegate void StateChangedResult(States newState);
        public event StateChangedResult onStateChange;
    }

    // Our actual program.  Simply create a traffic light instance
    // Register a callback that will simply print the current state returned 
    when the light state changes
    // And finally wait for the user to hit enter before ending the program
    public class Program
    {
        public static void Main(string[] args)
        {
            TrafficLight light = new TrafficLight();
            light.onStateChange += (TrafficLight.States state) => { Console.
            WriteLine(state); };
            Console.ReadLine();
        }
       
    }
}

The example is pretty well documented in the code above.  Essentially we are creating a class TrafficLight that can internally have one of three states Green, Yellow or Red.  It also implements a timer that switches between those states.  To make the code actually useful, it also implements a callback system so code external to the TrafficLight can interact with it as a black box.  The callback will be passed the current state value every time the light changes.

 

This is obviously a simple example of a state machine but the same basic premise remains regardless to complexity.  It is a very useful data structure for organizing code, especially the flow of logic.  Coupled with callbacks, it is also a great way of keeping systems decoupled as much as possible.

 

The Video

Programming, Design , ,

Month List

Popular Comments

Unity 3.4 has been released
Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon


27. July 2011

… so, go get it!  Download link.

For what’s new go here.  Lots of refinements and small fixes.

Programming

blog comments powered by Disqus

Month List

Popular Comments