Explore Free Babylon.js Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Thu, 23 Feb 2023 21:14:38 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free Babylon.js Tutorials – GameDev Academy https://gamedevacademy.org 32 32 How to Make an HTML5 Game https://gamedevacademy.org/how-to-make-a-html5-game/ Thu, 06 Jan 2022 09:30:39 +0000 https://gamedevacademy.org/?p=1585 Read more]]> Although Flash games have departed from this world, there is still a significant demand for browser-based and cross-platform games. Whether you yourself actively play them or not, more and more games from professional and indie developers alike come out each day.

This phenomenon is largely thanks to HTML5 games which have filled the gap to keep up with these eager gamers. In addition, thanks to the advancement of technology and new frameworks, HTML5 game development has reached extensive heights, allowing for multiplayer experiences, 3D graphics, and more! It is not unwise to say that gaming is now just as viable via a browser as it is on many other devices!

Assuming this sounds like an exciting prospect to you as a game developer, in this guide we’re going to delve into the topic of HTML5 game development and give you the run-down of how you can make your own games! Sit back, relax, and prepare to enhance your game development skills in entirely new ways!

What exactly is an HTML5 game?

Let’s start from total zero. What is HTML5? that’s a tricky question. There is an official definition of HTML5, which simply stands for the latest revision of HTML (the markup language used all over the world to build websites), and the more hyped definition (what most people understand when HTML5 is mentioned) which is all the “new” features of the web technologies that have come out in the last few years (JavaScript API’s like the Canvas or WebAudio, semantic HTML tags, etc).

For our purpose, we’ll use bits of the two. HTML5 is HTML in its latest version, which includes a whole bunch of cool features that make web technologies an open standard with endless possibilities combining HTML, CSS and JavaScript.

Having HTML along with all these superpowers that go beyond making a simple website allows us to make, among other things, games. These are HTML5 games.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

 Building blocks

The very basic building blocks of a HTML5 game are those of the web:

  • HTML
  • CSS
  • JavaScript

Similarly to what happens with HTML5, when people talk about CSS3 they usually refer to the new things that come with CSS’s latest specifications, but in an analog manner, CSS3 is simply the latest CSS. Ignoring for a second the semantics of these definitions and thinking of the hyped versions of these terms, we also may need, in order to make HTML5 games:

  • HTML5 (JavaScript API’s)
  • CSS3

With the above you can make awesome games that will run on modern web browsers on mobile and desktop, but some games might require more features, so there are more building blocks that you can add.

For instance, you may want to make 3D games. If that is the case there is also WebGL, which is a JavaScript API to render 2D and 3D graphics on the browser, using the GPU for greater performance.

Road crossing game made with HTML5

Server side

If you want your games to saved data remotely you’ll need a server-side for your game. You can develop your own backend using any server-side language, you’ll need well a server in this case.

  • JavaScript (NodeJS)
  • PHP
  • Java
  • Python
  • Ruby

Or you can use a third-party Backend-as-a-Service provider such as Firebase or Parse. Some have free versions you can use and they’ll start charging you once you surpass certain limits. Some of these providers are particularly focused on games, some are mostly conceived for mobile apps but can be used for games too.

How to distribute a HTML5 game

The easiest way to distribute a HTML5 is to simply put it out there! By being built as a website, you can just embed it in on a page and publish it. Just like that.

If you want to distribute it through proprietary platforms you have to go through a process called wrapping. Basically, you create a native app for the platform you wanna distribute it to (iOS, Android, etc) and put your game inside so that this app acts like a web browser and “runs” your game.

For desktop platforms such as Windows, Mac or Linux there is a tool called NWjs that allows you to pack your HTML5 games for these platforms.

We can only cover the basics here, but we encourage you to read our more in-depth advice about publishing games.

Match 3 game made with HTML5

HTML5 game frameworks

Most games share some concepts, that of sprites (graphic elements that represent enemies, players, elements in your game), scenes or stages, animations, sound, loading graphic assets, etc. Since most game developers want to focus on their actual game and not in creating this whole abstraction layer, it is recommended you use a HTML5 game frameworks.

HTML5 game frameworks and libraries that contain building components you can use to create your own games. These libraries are Open Source projects created and maintained by people who want to contribute to the HTML5 gamedev environment. In many cases they created the frameworks for their own games, and after realizing that other people would want to not only use it but also contribute to it they released them as Open Source code, so everybody wins.

Picking what game engine to use is an important decision, so make sure you do proper research before making your choice. No matter what engine you pick, you will have to get familiar with its code and inner working if you want to use properly, so they shouldn’t be treated as black boxes.

What can help you make your choice:

  • Is your game for desktop, mobile or both?
  • Do they have an active community?
  • Are there many people using the framework nowadays?
  • Is it being maintained or the Github page looks like an abandoned town?

Sometimes looking at real games gives you more insight than just words. This project compares different engines by making the exact same Breakout game in all of them.

Some popular free frameworks are:

Solar system project made with Babylon.js

HTML5 game development courses

Video courses are a great way to learn new technologies. The main difference between a video course and just watching YouTube videos is that there is more structure. Good courses have a clear goal and build on to it step by step. Below a list of courses and tutorials by Zenva that can give you the tools you need to create HTML5 games.

General Game Development

Phaser

WebGL, 3D, and XR

HTML5 Skills

At the GameDev Academy, as you know already we have a bunch of HTML5 game development tutorials, mostly on Phaser, LimeJs, Quintus and BabylonJS. There are other great places to find good quality HTML5 gamedev tuts:

HTML5 for Schools

Are you a teacher looking to help students get into frameworks like Phaser or teach them core and relevant web development skills? Try out Zenva Schools – an online platform offering coding-based courses for use in the classroom. The platform comes with video lessons, text summaries, quizzes, classroom management features, reporting, and more to help support learning HTML5!

HTML5 gamedev communities

You can find plenty of active communities on the Internet, some focus on gamedev in general and some others just in HTML5 gamedev.

Web:

Facebook:

Other Communities:

HTML5 gamedev challenges

  • The Global Game Jam® is an annual event, usually occurring in January every year. Participants work concurrently around the globe, and around a central theme, and then work together to create a game.
  • j13k competition: the competition is over but you can still read the Blog, subscribe to the Newsletter, and check the Resources for tools.

 HTML5 gamedev podcasts

I just know Lostcast, a podcast created by the guys from Lost Decade Games (whom we’ve interviewed in the past). In the podcast episodes they talk about they HTML5 games and game development in general.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Free Course – Get Started with Babylon.js https://gamedevacademy.org/babylonjs-tutorial/ Fri, 16 Oct 2020 01:00:24 +0000 https://coding.degree/?p=387 Read more]]>

Take your websites and HTML5 games to a whole new level with 3D graphics! With Babylon.js, you will learn to create novel 3D scenes that can be viewed right in your browser – a great choice for games or just any project you want to stand out on the web. You can also extend the material covered here by checking out the full course below!

Build 3D Web Apps with Babylon.js

About

Babylon.js is a powerful rendering engine that utilizes the HTML Canvas to display 3D graphics in your browser – thanks to WebGL technology. With the instructor, Scott Westover, you will explore both how to set up Babylon.js for your own projects, and also how to utilize basic aspects of the API to add primitive 3D models to your scene. Whether you’re looking to create beautiful websites, exciting browser games, or simply want something to add to your portfolio, these skills will help enhance your skills in unique ways from other developers!

]]>
3D Programming with WebGL and Babylon.js for Beginners https://gamedevacademy.org/3d-programming-with-webgl-and-babylon-js-for-beginners/ Fri, 08 Jul 2016 11:00:38 +0000 https://gamedevacademy.org/?p=3836 Read more]]> You can display 3D images in all browsers without the use of plugins. This course shows you how to use WebGL and Babylon.js to create 3D scenes and animations. Use existing 3D models from Blender and incorporate Babylon.js into existing websites.

Give yourself the basic tools to build 3D games for browsers, display 3D models such as the human body in educational websites, 3D data visualization, 3D display of products for ecommerce, real estate walkthroughs, virtual reality and more. Be part of the coolest web development going on today.

Access this course on Zenva Academy

]]>
Babylon.JS Multi-material Tutorial https://gamedevacademy.org/babylon-js-multi-material-tutorial/ Wed, 07 May 2014 12:32:32 +0000 https://gamedevacademy.org/?p=1715 Read more]]> Learn WebGL and Babylon.js at your own pace

Feel free to check out our online course 3D Programming with WebGL and Babylon.js for Beginners on Zenva Academy. The course covers the Babylon.js framework and explains all you need to get started with using this fantastic library in new or existing projects.

Tutorial

A multi-material is used to apply different materials to different parts of the same object as you can see in this screen capture (from www.babylonjs.com):

image

To be able to define a multi-materials you first have to define some standard materials:

    var material0 = new BABYLON.StandardMaterial("mat0", scene);
    material0.diffuseColor = new BABYLON.Color3(1, 0, 0);
    material0.bumpTexture = new BABYLON.Texture("normalMap.jpg", scene);

    var material1 = new BABYLON.StandardMaterial("mat1", scene);
    material1.diffuseColor = new BABYLON.Color3(0, 0, 1);

    var material2 = new BABYLON.StandardMaterial("mat2", scene);
    material2.emissiveColor = new BABYLON.Color3(0.4, 0, 0.4);

Then you can create a multi-material in order to gather them all:

var multimat = new BABYLON.MultiMaterial("multi", scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
multimat.subMaterials.push(material2);

You are now able to affect the multi-material to your mesh:

var sphere = BABYLON.Mesh.CreateSphere("Sphere0", 16, 3, scene);
sphere.material = multimat;

But if you do that, you will see that the sphere will only use the first submaterial (the red bumped one). This is because by default a mesh is is designed to use only one material.

You can specify which part of the mesh uses a specific material by using the subMeshes property. By default, every mesh comes with only one submesh that cover the entire mesh.

To define multiple submeshes, you just have to use this code:

sphere.subMeshes = [];
var verticesCount = sphere.getTotalVertices();

sphere.subMeshes.push(new BABYLON.SubMesh(0, 0, verticesCount, 0, 900, sphere));
sphere.subMeshes.push(new BABYLON.SubMesh(1, 0, verticesCount, 900, 900, sphere));
sphere.subMeshes.push(new BABYLON.SubMesh(2, 0, verticesCount, 1800, 2088, sphere));

In this case, we will have 3 parts:

  • One starting from index 0 to index 900
  • One starting from index 900 to index 1800
  • One starting from index 1800 to index 3880

A submesh is defined with:

  • The index of the material to use (this index is used to find the correct material Inside the subMaterials collection of a multi-material)
  • The index of the first vertex and the count of vertices used (To optimize things for collisions for instance)
  • Index of the first indice to use and indices count
  • The parent mesh

So with the code below, we can use the first material on the top part of the sphere, the second material on the middle part and the last material on the bottom part of the sphere.

]]>
Creating a 3D chart for your Windows 8.1 app using Babylon.js https://gamedevacademy.org/creating-a-3d-chart-for-your-windows-8-1-app-using-babylon-js/ Wed, 23 Apr 2014 12:25:12 +0000 https://gamedevacademy.org/?p=1727 Read more]]> Learn WebGL and Babylon.js at your own pace

Feel free to check out our online course 3D Programming with WebGL and Babylon.js for Beginners on Zenva Academy. The course covers the Babylon.js framework and explains all you need to get started with using this fantastic library in new or existing projects.

Tutorial

Windows 8.1 added the support of WebGL for Internet Explorer and JavaScript applications. This is a huge evolution because we are now able to unleash the raw power of the GPU even with HTML5 and JavaScript!

This power can be tricky to master and that’s why I created babylon.js. And using it, the wonderful world of accelerated 3D will welcome you.

Preparing the project

For instance, I always wanted to create an app to have my blog’s statistics at a glance.

If you want to get the final application, you can download the complete project here (127KB)

To do so, let’s start with a empty Windows 8.1 JavaScript app.

image

The first thing is to reference babylon.js (and hand.js for supporting touch events):

image

The default.html page should be changed to add a canvas and to reference babylon.js and hand.js:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Chart3D</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.2.0.Preview/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.2.0.Preview/js/base.js"></script>
    <script src="//Microsoft.WinJS.2.0.Preview/js/ui.js"></script>

    <!-- Chart3D references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="js/hand.minified-1.1.1.js"></script>
    <script src="js/babylon.js"></script>
    <script src="/js/default.js"></script>
</head>
<body>
    <canvas id="renderCanvas"></canvas>
</body>
</html>

Connecting babylon.js

As you may have seen in my previous postsbabylon.js needs to connect with the canvas through the BABYLON.Engine object. We can do that right after the completion of the processAll function:

args.setPromise(WinJS.UI.processAll().then(function() {
                var canvas = document.getElementById("renderCanvas");
                var engine = new BABYLON.Engine(canvas, true);

Then we have to create some entities required to generate a complete scene:

var scene = new BABYLON.Scene(engine);
var light = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(0, -0.5, 1.0), scene);
var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 10, BABYLON.Vector3.Zero(), scene);
camera.setPosition(new BABYLON.Vector3(20, 70, -100));
light.position = new BABYLON.Vector3(0, 25, -50);

The scene, a light and a camera to define the user’s point of view. Nothing special here.

Finally we have to connect the camera with the canvas (to allow the user to control the camera) and launch the render loop:

// Render
camera.attachControl(canvas);

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

// Resize
window.addEventListener("resize", function () {
    engine.resize();
});

Creating the ground and the background

If we launch our app right now, it will be a little bit empty. Indeed there is nothing to display Sourire

Let’s add the ground and the background to create something like this:

image

The ground will be generated with BABYLON.Mesh.CreateGround (!!) and the background with BABYLON.Mesh.CreatePlane:

var playgroundSize = 100;
// Background
var background = BABYLON.Mesh.CreatePlane("background", playgroundSize, scene, false);
background.material = new BABYLON.StandardMaterial("background", scene);
background.scaling.y = 0.5;
background.position.z = playgroundSize / 2 - 0.5;
background.position.y = playgroundSize / 4;

var backgroundTexture = new BABYLON.DynamicTexture("dynamic texture", 512, scene, true);
background.material.diffuseTexture = backgroundTexture;
background.material.specularColor = new BABYLON.Color3(0, 0, 0);
background.material.backFaceCulling = false;

backgroundTexture.drawText("Eternalcoding", null, 80, "bold 70px Segoe UI", "white", "#555555");
backgroundTexture.drawText("- browsers statistics -", null, 250, "35px Segoe UI", "white", null);

// Ground    
var ground = BABYLON.Mesh.CreateGround("ground", playgroundSize, playgroundSize, 1, scene, false);
var groundMaterial = new BABYLON.StandardMaterial("ground", scene);
groundMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
groundMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
ground.material = groundMaterial;

ground.position.y = -0.1;

The main point to note here is the usage of a BABYLON.DynamicTexture: This object allows you to draw in a texture with a canvas. There are also some handy functions like drawText to simplify complex tasks. Instead of using drawText you could have written the following code (just for the sake ofcomprehension):

 BABYLON.DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
     var size = this.getSize();
     if (clearColor) {
         this._context.fillStyle = clearColor;
         this._context.fillRect(0, 0, size.width, size.height);
     }

     this._context.font = font;
     if (x === null) {
         var textSize = this._context.measureText(text);
         x = (size.width - textSize.width) / 2;
     }

     this._context.fillStyle = color;
     this._context.fillText(text, x, y);

     this.update(invertY);
 };

As you can see this is a regular 2D canvas code.

Adding the series’ data

Now it is time to add some data to display. For not complicating things up, we will consider static data but obviously you are free to use dynamic data:

var browsers_Series = [
    { label: "IE", value: 32, color: new BABYLON.Color3(0, 0, 1) },
    { label: "Chrome", value: 28, color: new BABYLON.Color3(1, 0, 0) },
    { label: "Firefox", value: 16, color: new BABYLON.Color3(1, 0, 1) },
    { label: "Opera", value: 14, color: new BABYLON.Color3(1, 1, 0) },
    { label: "Safari", value: 10, color: new BABYLON.Color3(0, 1, 1) }
];

Every entry is composed of a label, a value (which is a percentage) and a color.

To display them, we have to add a new function in our code:

var createSeries = function (series) {
    var margin = 2;
    var offset = playgroundSize / (series.length) - margin;
    var x = -playgroundSize / 2 + offset / 2;

    for (var index = 0; index < series.length; index++) {
        var data = series[index];

        var bar = BABYLON.Mesh.CreateBox(data.label, 1.0, scene, false);
        bar.scaling = new BABYLON.Vector3(offset / 2.0, data.value * scale, offset / 2.0);
        bar.position.x = x;
        bar.position.y = data.value * scale / 2.0;

        // Material
        bar.material = new BABYLON.StandardMaterial(data.label + "mat", scene);
        bar.material.diffuseColor = data.color;
        bar.material.emissiveColor = data.color.scale(0.3);
        bar.material.specularColor = new BABYLON.Color3(0, 0, 0);

        // Going next
        x += offset + margin;
    }
};

For each entry, we create a box associated with a colored material. The box is then scaled depending on the entry’s value. The result is the following screen:

image

Shadows

The previous screen may look a bit flat. We can improve things up by adding dynamic shadows.

Real-time shadows are complex to produce (you need to create a shadow map and then use it in your shaders). But with babylon.js, you just have to create a BABYLON.ShadowGenerator and define which objects cast shadows and which objects receive shadows:

// Shadows
var shadowGenerator = new BABYLON.ShadowGenerator(1024, light);
ground.receiveShadows = true;
background.receiveShadows = true;

To cast shadows, boxes must be added to the shadowGenerator object:

shadowGenerator.getShadowMap().renderList.push(bar);

The result is more beautiful, isn’t it?

image

Adding the legend

There is an issue with our chart: no one can say the value and the associated label of each box. That is why we need to add a legend.

Every box will be associated with a small plane with a dynamic texture filled with the label and the value of the current entry:

image

To do so, we have to update our createSeries function in order to generate a legend for each entry:

// Legend
var barLegend = BABYLON.Mesh.CreateGround(data.label + "Legend", playgroundSize / 2, offset * 2, 1, scene, false);
barLegend.position.x = x;
barLegend.position.z = -playgroundSize / 4;
barLegend.rotation.y = Math.PI / 2;

barLegend.material = new BABYLON.StandardMaterial(data.label + "LegendMat", scene);
var barLegendTexture = new BABYLON.DynamicTexture("dynamic texture", 512, scene, true);
barLegendTexture.hasAlpha = true;
barLegend.material.diffuseTexture = barLegendTexture;
barLegend.material.emissiveColor = new BABYLON.Color3(0.4, 0.4, 0.4);

var size = barLegendTexture.getSize();
barLegendTexture.drawText(data.label + " (" + data.value + "%)", 80, size.height / 2 + 30, 
                                       "bold 50px Segoe UI", "white", "transparent", false);

Sprinkling a bit of animations

Finally for the “waoouh” effect, I suggest we can animate the boxes: They will start with a 0 height and they will grow up to their effective value:

var bar = BABYLON.Mesh.CreateBox(data.label, 1.0, scene, false);
bar.scaling = new BABYLON.Vector3(offset / 2.0, 0, offset / 2.0);
bar.position.x = x;
bar.position.y = 0;

// Animate a bit
var animation = new BABYLON.Animation("anim", "scaling", 30, BABYLON.Animation.ANIMATIONTYPE_VECTOR3);
animation.setKeys([
    { frame: 0, value: new BABYLON.Vector3(offset / 2.0, 0, offset / 2.0) },
    { frame: 100, value: new BABYLON.Vector3(offset / 2.0, data.value * scale, offset / 2.0) }]);
bar.animations.push(animation);

animation = new BABYLON.Animation("anim2", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT);
animation.setKeys([
    { frame: 0, value: 0 },
    { frame: 100, value: (data.value * scale) / 2 }]);
bar.animations.push(animation);
scene.beginAnimation(bar, 0, 100, false, 2.0);

You can note that we create two animations: one for the scaling and one for the position (the pivot of each box is in the middle of the mesh).  Thescene.beginAnimation is then used to launch to animation.

Nothing complex here but a cool effect for the user Sourire

Conclusion

If you want to go further, you can consider embedding this code in a control and work with dynamic data to achieve a really mind-lowing way to display data.

 

]]>
Interactive Games with WebGL, Babylon.js, and Cannon.js https://gamedevacademy.org/create-wonderful-interactive-games-for-the-web-using-webgl-and-a-physics-engine-babylon-js-cannon-js/ Mon, 14 Apr 2014 12:35:44 +0000 https://gamedevacademy.org/?p=1740 Read more]]> Learn WebGL and Babylon.js at your own pace

Feel free to check out our online course 3D Programming with WebGL and Babylon.js for Beginners on Zenva Academy. The course covers the Babylon.js framework and explains all you need to get started with using this fantastic library in new or existing projects.

Tutorial

Did you ever notice how a physics game is addictive? Actually, I can spend hours playing with small physics simulations just because it looks so real.
image

That’s why I decided to integrate a physics engine into babylon.js.

Can’t wait and want to play right now? Just go there..

State of the art

The purpose was not to create a physics engine from scratch., There are already a few good physics engine written for JavaScript by the community (This is one of the reason why I love JavaScript: there is always a .js project for what you want to do ^^)Here are some examples (I do not talk about 2D engine but only 3D ones):

  • Cannon.js: A pure JavaScript engine. I decided to use this one because the code is clear, efficient and very well maintained
  • JigLibJS: A JavaScript port of a C/C++ library called JigLib
  • Ammo.js: A JavaScript port of Bullet engine.The port was made using Emscripten and thus this is an automated port.
  • Bullet.js: Another JavaScript port of Bullet

All of these engines are great but I had to make a choice. So I decided to use a purely JavaScript engine (in opposite to a port of an existing one) because I wanted an engine designed and thought for JavaScript.

For instance, I did not keep Ammo.js because it was created with Emscripten. Because of how Emscripten converts libraries to Javascript there are some things in Ammo.js which are more difficult to use – pointers for instance add an extra layer of complication.

Because they are ports and not written in Javascript, they are not optimized for the web. Javascript has its own features and quirks which make developing for it unique.

Activating physics with babylon.js

So let’s go back to Babylon.js. From the point of view of a web developer, physics engine can give you a lot of cool features among which we can get for instance:

  • Realistic simulation of basic shapes (Box, Sphere, compound, etc…)
  • Simulation of friction and bounciness
  • Link between objects (to simulate chains for instance)

So let’s have a look on how to activate all these funny things with Babylon.js:

Enabling physics engine

To enable the physics engine, you just have to run this line of code:

scene.enablePhysics();

Please note that the physics simulation can be really expensive when it comes to talk about performance

You can define the gravity of your simulation with the following command:

scene.setGravity(new BABYLON.Vector3(0, -10, 0));

Defining impostors for your meshes

The simulation will not directly work on your meshes (far too complex). Actually, you will need to create a geometric impostor for them. Right now, I only support boxes, spheres and planes but in a not too distant future I will continue adding new impostors.

To define an impostor, you just have to call the setPhysicState function:

sphere.setPhysicsState({ impostor: BABYLON.PhysicsEngine.SphereImpostor, mass: 1 });

The mass parameter can be set to 0 if you want to create a static object (such as a ground for instance).

You can also define the friction (resistance of the object to movement) and the restitution (tendency of the object to bounce after colliding with another):

ground.setPhysicsState({ impostor: BABYLON.PhysicsEngine.BoxImpostor, mass: 0, friction: 0.5, restitution: 0.7 });

The initial position and rotation (using mesh.rotationQuaternion property) of the mesh are used to define the position and rotation of the impostors.

Creating links

You can also link your impostors in order to always keep meshes linked. You can for instance create chains like this one:

image

To do so, you just have (as always) one line of code to execute:

spheres[index].setPhysicsLinkWith(spheres[index + 1], new BABYLON.Vector3(0, 0.5, 0), new BABYLON.Vector3(0, -0.5, 0));

Creating compound impostors

If you want to create more complex physics objects you can use the scene.createCompoundImpostor function:

// Compound
var part0 = BABYLON.Mesh.CreateBox("part0", 3, scene);
part0.position = new BABYLON.Vector3(3, 30, 0);

var part1 = BABYLON.Mesh.CreateBox("part1", 3, scene);
part1.parent = part0; // We need a hierarchy for compound objects
part1.position = new BABYLON.Vector3(0, 3, 0);

scene.createCompoundImpostor({
    mass: 2, friction: 0.4, restitution: 0.3, parts: [
    { mesh: part0, impostor: BABYLON.PhysicsEngine.BoxImpostor },
    { mesh: part1, impostor: BABYLON.PhysicsEngine.BoxImpostor }]
});

This will create an unique rigid body object based on the hierarchy provided.

Beware, to create a compound impostor, you must create a hierarchy and provide the root as first object

Applying an impulse

Once your scene is set up, you can play with your meshes using this code:

var pickResult = scene.pick(evt.clientX, evt.clientY);
var dir = pickResult.pickedPoint.subtract(scene.activeCamera.position);
dir.normalize();
pickResult.pickedMesh.applyImpulse(dir.scale(10), pickResult.pickedPoint);

This will apply an impulse on the selected mesh at a given point (in world space).

Exporting a blender scene with physics enabled

Thanks to the extensibility capabilities of Blender (with Python Sourire), I was able to support exporting physics information.

You just have to select a mesh and directly go to the Physics tab:

image

Blender will not let you define a mass equal to zero. But do not worry about that because the exporter will consider a value of 0.001 as zero.

Then, you will be able to define mass, shape, friction and restitution (Bounciness):

image

And you’re done! Simply export your scene to a .babylon file and use it in your own app/site Sourire or drag’n’drop it to our sandbox.

The power of the web

I keep being amazed by the power of current browsers. Right now, you can have a complete 3D simulation alongside an accurate physics engine. And that, with only a few lines of JavaScript code!!

You have now everything you need to create wonderful and dynamic games for the web and for Windows 8! So let’s unleash your creativity. Who knows, the next Angry Bird is perhaps a few lines of code away Sourire

]]>
Advanced Texturing – BabylonJS Series part 14 https://gamedevacademy.org/advanced-texturing-babylonjs-series-part-14/ Tue, 12 Nov 2013 12:27:01 +0000 https://gamedevacademy.org/?p=1093 Read more]]> Learn WebGL and Babylon.js at your own pace

Feel free to check out our online course 3D Programming with WebGL and Babylon.js for Beginners on Zenva Academy. The course covers the Babylon.js framework and explains all you need to get started with using this fantastic library in new or existing projects.

Tutorial

You have already seen how you can apply some textures on meshes, but here you are going one step further, with more complex textures like mirrors, videos, bump mapping, and multi-texture.

AdvancedTexturing

Final result

How can I do this ?

Those new type of textures are considered advanced because we are not used to deal with them, but you’ll see that it is very easy to develop them in JavaScript!

  • Mirror

Mirrors textures were created to simulate “mirrors” (!) which mean that babylon.js will compute for you the reflection and fill the texture with the results. A Mirror texture must be set in the reflectionTexture channel of a standardMaterial :

var mirrorMaterial = new BABYLON.StandardMaterial("texture4", scene);
mirrorMaterial.reflectionTexture = new BABYLON.MirrorTexture("mirror", 512, scene, true);
mirrorMaterial.reflectionTexture.mirrorPlane = new BABYLON.Plane(0, -1.0, 0, -10.0);
mirrorMaterial.reflectionTexture.renderList = [sphere1, sphere2];

mirrorTexture is created with a parameter that specify the size of the rendering buffer (512×512 here, better reflection quality if increased). Then you have to define the reflection plane and a render list (the list of meshes to render inside the mirror).

  • Bump Mapping

Bump mapping is a technique in computer graphics to make a rendered surface look more realistic without modifying surface geometry. This is only a texture modification, so computation is the same but rendering is much better, have a look:

bumpMap

The bump texture simulates bumps and dents using a map called a normal map.

normalMap

A normal map

And now, let’s code this amazing texture within two lines of JavaScript: first we create a new standard material, and then, simply declare a new bump texture:

var bumpMaterial = new BABYLON.StandardMaterial("texture1", scene);
bumpMaterial.bumpTexture = new BABYLON.Texture("normalMap.jpg", scene);

That’s it, the bump texture disturbs the normal to produce a result like this, where you should recognize our normal map:

finalResult

  • Video

If you want to display a movie in your scene, Babylon engine have a special texture, which is working as all the other ones, with a few parameters, including videos urls (an url array), the size of the video texture (here is 256), the scene and the last one is a boolean, if you want to use mipmap or not.

ecran.material.diffuseTexture = new BABYLON.VideoTexture("video", 
["Scenes/Flat2009/babylonjs.mp4", "Scenes/Flat2009/babylonjs.webm"], 256, scene, true);

video

The VideoTexture object accepts an array of videos (to take in account various codecs) and once a video can be loaded, it uses it as content source. The internal video DOM object is accessible via VideoTexture.video property to allow you to control the status of the video (play/pause/stop).

You can also change the loop or autoplay parameter with a boolean variable.

  • Multi materials

Using a dedicated texture, multi materials can be assigned to one single mesh. It can be useful if you want that your mesh looks different depending of height, or depth, or… E.g. you can see below a map with multi materials texture (sand, rock, and snow).

multimap

To talk about multi materials, you have a strong blog post on David Catuhe’s blog:http://blogs.msdn.com/b/eternalcoding/archive/2013/07/10/babylon-js-using-multi-materials.aspx

]]>
Loading Scenes from Blender – BabylonJS Series part 13 https://gamedevacademy.org/loading-scenes-from-blender-babylonjs-series-part-13/ Tue, 05 Nov 2013 12:25:10 +0000 https://gamedevacademy.org/?p=1090 Read more]]> Learn WebGL and Babylon.js at your own pace

Feel free to check out our online course 3D Programming with WebGL and Babylon.js for Beginners on Zenva Academy. The course covers the Babylon.js framework and explains all you need to get started with using this fantastic library in new or existing projects.

Tutorial

This tutorial is going to teach you how you can load a complete scene from Blender, directly to BabylonJS ! Babylon engine can load an entire scene, or simply one 3D object.

The main idea is to export your scene to a .babylon format, and load it in your javascript code. Blender has been chosen as our default modeling software because it’s free and open-source, as BabylonJS.

Blender

How can I do this ?

Everything you need to know for Blender is on David Catuhe’s blog

Once you konw that, you could manipulate complex meshes, and I’m pretty sure you will be interested in learning advanced texture techniques.

]]>
How to Create Particle Systems – BabylonJS Series part 12 https://gamedevacademy.org/how-to-create-particle-systems/ Tue, 29 Oct 2013 12:23:16 +0000 https://gamedevacademy.org/?p=1087 Read more]]> Learn WebGL and Babylon.js at your own pace

Feel free to check out our online course 3D Programming with WebGL and Babylon.js for Beginners on Zenva Academy. The course covers the Babylon.js framework and explains all you need to get started with using this fantastic library in new or existing projects.

Tutorial

This tutorial is going to talk about particle system in BabylonJS. Particles are often small sprites used to simulate hard to reproduce phenomena like fire, smoke, water, or abstract visual effect like magic.

Particles

Final result

How can I do this ?

To perform this magic trick, the first thing to do is to create a new object, which will be our emitter. In our case, a box will be our rendering object, representing our fountain.

var fountain = BABYLON.Mesh.CreateBox("foutain", 1.0, scene);

The emitter acts as the source of the particles, and its location in 3D space determines where they are generated and whence they proceed. So pay attention to the location/rotation of this object. In our case, the emitter is our fountain, but if you need, you can use only a vector (BABYLON.Vector3) as an emitter.

Now, get into the particle system by creating a new ParticleSystem object:

var particleSystem = new BABYLON.ParticleSystem("particles", 2000, scene);

Nothing really new, except the second parameter, which is the maximum number of particles. Now an important part is to define the texture of each particle. Each one have the same pattern, so choose carefully which one you want. Our particle picture is going to be this one:

Flare

To define particle’s texture, you just have to write:

particleSystem.particleTexture = new BABYLON.Texture("Flare.png", scene);

On this texture, you can use an optional mask to filter some colors, or a part of the alpha channel.

particleSystem.textureMask = new BABYLON.Color4(0.1, 0.8, 0.8, 1.0);

This is the output of this configuration:

TextureMask

The last main thing to do is to define our emitter that we have talked about earlier:

// Where the particles comes from
particleSystem.emitter = fountain; // the starting object, the emitter

Now you should see your particle systems working. But it won’t be our final result before we refine some parameters:

  • Box around our emitter. Our emitter is the center of particles source, but if you want that your particles emits from more than one point, then you can define an entire box:
    particleSystem.minEmitBox = new BABYLON.Vector3(-1, 0, 0); // Starting all From
    particleSystem.maxEmitBox = new BABYLON.Vector3(1, 0, 0); // To...

Like you can see, particles are emitted from different position on X-axis:

EmitBox

  • Now you can give some colors to your particles. Color one and two are combined, and the “colorDead” is the color that take the particle before it disappears.
    // Colors of all particles (splited in 2 + specific color before dispose)
    particleSystem.color1 = new BABYLON.Color4(0.7, 0.8, 1.0, 1.0);
    particleSystem.color2 = new BABYLON.Color4(0.2, 0.5, 1.0, 1.0);
    particleSystem.colorDead = new BABYLON.Color4(0, 0, 0.2, 0.0);
  • Size of particles:
    // Size of each particle (random between...)
    particleSystem.minSize = 0.1;
    particleSystem.maxSize = 0.5;
  • LifeTime of particles:
    // Life time of each particle (random between...)
    particleSystem.minLifeTime = 0.3;
    particleSystem.maxLifeTime = 1.5;
  • Emit rate. This is the density of particles, the rate of particles flow:
    particleSystem.emitRate = 1000;

emitRate

Now something that can be interesting if you want to launch only a few particles at once, for example if you want to emit only 300 particles:

particleSystem.manualEmitCount = 300;

Be warned, the stream is no more continuous, this is a one-shot particle emission, so this function is erasing the previous “emitRate” parameter.

  • The selected mode for particles. You can choose between “BLENDMODE_ONEONE” (default choice: source color is added to the destination color without alpha affecting the result), and “BLENDMODE_STANDARD” (to blend current color and particle color using particle’s alpha).
    particleSystem.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  • Gravity. You can use gravity if you want to give an orientation to your particles (e.g.: fire particles are going up on Y-axis)
    //Set the gravity of all particles (not necessary down)
    particleSystem.gravity = new BABYLON.Vector3(0, -9.81, 0);
  • Direction. Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
    particleSystem.direction1 = new BABYLON.Vector3(-7, 8, 3);
    particleSystem.direction2 = new BABYLON.Vector3(7, 8, -3);

emitRate

  • AngularSpeed. You can define a rotation for each particle (in radian):
    particleSystem.minAngularSpeed = 0;
    particleSystem.maxAngularSpeed = Math.PI;
  • Speed/Strength. You can define the power in emitting particles, and the overall motion speed (0.01 is default update speed, faster updates = faster animation).
    particleSystem.minEmitPower = 1;
    particleSystem.maxEmitPower = 3;
    
    particleSystem.updateSpeed = 0.005;
  • Duration. You can set the amount of time the particle system is running (depends of the overall speed above).
    particleSystem.targetStopDuration = 5;
  • Dispose. Disposes or not the particle system on stop (very useful if you want to create a one shot particle system with a specific targetStopDuration):
    particleSystem.disposeOnStop = true;

Finally, you can start this particle system whenever you want in your code with:

particleSystem.start();

And naturally stop it:

particleSystem.stop();

]]>
Grabbing 3D Objects with the Mouse – BabylonJS Series part 11 https://gamedevacademy.org/grabbing-3d-objects-with-the-mouse-babylonjs-series-part-11/ Tue, 22 Oct 2013 12:21:09 +0000 https://gamedevacademy.org/?p=1084 Read more]]> Learn WebGL and Babylon.js at your own pace

Feel free to check out our online course 3D Programming with WebGL and Babylon.js for Beginners on Zenva Academy. The course covers the Babylon.js framework and explains all you need to get started with using this fantastic library in new or existing projects.

Tutorial

The last collision type could be very useful for you: it’s picking an object with your mouse. The main difficulty is to click on a 3D object whereas your screen is a flat 2D display.

Let’s see how we can get your mouse position transposed in your 3D scene by this gun shooting example:

Picking

Final result

How can I do this ?

Babylon engine let you do this very easily by giving you useful functions.

First of all, after creation of a plane representing the wall, and a plane with our impact’s picture, we have to detect a click on the UI (User Interface). Once the event is raised, use the function “pick” to get some powerful information about the relation between your click and your scene.

//When click event is raised
window.addEventListener("click", function (evt) {
   // We try to pick an object
   var pickResult = scene.pick(evt.clientX, evt.clientY);
});

The pickResult object is mainly composed of 4 information:

  1. hit (bool): « True » if your click hits an object in the scene.
  2. distance (float): the “distance” between the active camera and your hit (infinite if no mesh selected)
  3. pickedMesh (BABYLON.Mesh): if you hits an object, this is the selected mesh. If not, it’s null.
  4. pickedPoint (BABYLON.Vector3): the point you have clicked, transformed in 3D coordinates depending on the object you’ve clicked. Null if no hits.

Now we have all the data we needed to build our scene. We just have to position our gun’s impact when the user clicks on the plan:

// if the click hits the ground object, we change the impact position
if (pickResult.hit) {
            impact.position.x = pickResult.pickedPoint.x;
            impact.position.y = pickResult.pickedPoint.y;
}

Fast, and easy, isn’t it?

]]>