Home Game Development Going the Distance with Babylon.js

Going the Distance with Babylon.js

By Josh Elster
books-svg-icon Book
eBook $33.99
Print $41.99
Subscription $15.99
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $33.99
Print $41.99
Subscription $15.99
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: The Space-Truckers Operation Manual
About this book
Babylon.js allows anyone to effortlessly create and render 3D content in a web browser using the power of WebGL and JavaScript. 3D games and apps accessible via the web open numerous opportunities for both entertainment and profit. Developers working with Babylon.js will be able to put their knowledge to work with this guide to building a fully featured 3D game. The book provides a hands-on approach to implementation and associated methodologies that will have you up and running, and productive in no time. Complete with step-by-step explanations of essential concepts, practical examples, and links to fully working self-contained code snippets, you’ll start by learning about Babylon.js and the finished Space-Truckers game. You’ll also explore the development workflows involved in making the game. Focusing on a wide range of features in Babylon.js, you’ll iteratively add pieces of functionality and assets to the application being built. Once you’ve built out the basic game mechanics, you’ll learn how to bring the Space-Truckers environment to life with cut scenes, particle systems, animations, shadows, PBR materials, and more. By the end of this book, you’ll have learned how to structure your code, organize your workflow processes, and continuously deploy to a static website/PWA a game limited only by bandwidth and your imagination.
Publication date:
September 2022
Publisher
Packt
Pages
426
ISBN
9781801076586

 

The Space-Truckers Operation Manual

It’s not considered to be a very emotionally evolved stance to judge a book by its cover, but have you seen the cover of this book? If it’s something you like, then please, by all means, do judge this book by its cover, you counter-culture influencer, you – carry on reading!

If for some reason you don’t like the cover, then bully for you for literally turning over a new page to see what’s inside – unlike some superficial cretins. We’re above that sort of petty judgment, after all.

Note

Sometimes, relevant information will be presented in these Note boxes. Other times, these same boxes will contain completely irrelevant but possibly irreverent information. At all times, or at none (sometimes), should you pay attention to what’s in these boxes.

Regardless of whether you’re on Team Cover or Team Content, it’s clear you’re incredibly smart and well mannered for the simple fact that you’ve started reading this book. We’re about to embark on a journey together over the next 14 chapters. This is not the type of journey that you might encounter flipping through channels while you search for something to watch before bedtime. This is a journey across the wide and vast terrain that is the Babylon.js ecosystem. It isn’t a safari, but it is a sojourn. One thing it is not, however, is an Odyssey. Primarily because you don’t have to actually go anywhere, and you get to go back to your regular life whenever you’re not reading this book, but perhaps for other reasons too.

Important Note

Like its less-distinguished cousin the Note, Important Note boxes will occasionally make an appearance. Generally, these are used for Things You Might Regret Not Knowing About Before…

We are going to cover a huge amount of ground over the course of our sojourn, our journey, but you won’t be traveling unprepared. Our overall objective here is to build a game hosted by and in a generic web application. Over the course of three separate parts, we’re going to progressively do three things:

  • Create and set up an application and development workflow that gives Space-Truckers: The Video Game! a place to live
  • Layer on additional functionality to our application (hosting Space-Truckers: The Video Game!)
  • Zoom out on the level of detail to take on a wide range of enhancements and add to our good knowledge

Each chapter will build on the work established in the previous chapter. It’s possible that the code in one chapter will need to be modified in subsequent chapters, and that should be looked at as a reflection of our evolving understanding of how the application needs to be structured to accomplish the goal at hand. Every chapter (save this one) contains links to the game’s code in the same context as the chapter’s text, in addition to live demos and Playground links specific to the content.

While we are building upon the application, we will also be providing fewer and fewer line-by-line code details in favor of providing extra context and/or information relating to how something works “under the hood.” Don’t worry, the code and Playground samples are still there to help you find your way! We’ll be exploring concepts that in themselves can occupy entire texts longer than this not-very-short book, and we’ll be doing so with less room to expand on those same topics. As a result, we will be looking to cover some areas at a high level while others will be discussed to a greater depth.

We’re going to start by walking through the game from the standpoint of the player, then we’ll move on to look at the underlying game and application design. As a finisher, we wrap this first travel segment up with a tour of the Space-Truckers GitHub repository and other online resources. Let’s start with the ending, in classic literary fashion.

Note

For the movie version of this scene, picture a shimmering dissolve with appropriate sound effects as we transition to a different world…

 

Introducing the World of Space-Truckers

Astronomers recently started receiving a mysterious signal, apparently from outside of our Solar System. Far from being random noise, the signal appears to contain structured data in the form of text, audio, and visual content – an alien transmission! The transmission starts with a basic primer on terminology and math and rapidly works its way up to describing some sort of large plastic disc imprinted with something the message called “multi-media interactive content” that is then connected to a display device and spun around (how ludicrous!) at thousands of RPMs while a laser beam reads grooves burned into the spinning disc. Laser beams. Grooves. Spinning wheels. All ridiculous, but there’s no accounting for alien sensibilities, right?

The following is a reconstruction of the content that was recovered from that transmission and burned onto what is now known as the “Dead Sea CD.” Due to the nature of its journey through space and time, parts of the transmission were not received, and the data contained was unrecoverable. At the same time, the connected nature of the data resulted in other parts being corrupted. Consequently, many of the images and still frames you are about to view represent data that has been patched back together using the best tools and resources at our disposal.

Talented teams of professional engineers, scientists, and even sociologists have worked long and hard to bring about this reconstructed image of what we believe the people who left us – or sent to us – this record look like:

Figure 1.1 – Best guess at the appearance of the originators of the Space-Truckers transmission

Figure 1.1 – Best guess at the appearance of the originators of the Space-Truckers transmission

The next section contains the reconstructed text and image content recovered from the transmission. Because the original message was expressed symbolically and not in any human language, the latest GPT-3 text generation AI was trained on the transmission’s symbols so that it could then produce the content that follows and format it consistently with the rest of this book.

 

So, You Wanna be a Space-Trucker?

BEGIN TRANSMISSION

Figure 1.2 – Reconstruction of the Space-Truckers transmission. Probably intended as a “day in the life” image

Figure 1.2 – Reconstruction of the Space-Truckers transmission. Probably intended as a “day in the life” image

Being a Space-Trucker isn’t for the faint of heart, nor is it for the lonely of mind. There are hazards and dangers to be found in spades – but there’s also the allure of fortune and fame. Ever since legendary Space-Trucker Winchell Chung’s (call sign: Rocket Cat) famous “Grand Tour,” every kid across the system has grown up aspiring to emulate him. After using the last of his reaction mass to deliver his cargo, he saved millions of starving children suffering after the Great Space-Potato Famine. Sadly, that selfless act left his Space-Rig adrift with no way home. Chung’s Space-Truck was lost as it drifted off into the Darkness Beyond the Sun. His last transmission, garbled as it was, contained a single recoverable fragment of text:

“The cold, hard equations care not for starvation or famine. <indecipherable>…[b]ecause we’re Space-Truckers. It’s what we do.”

Space-Trucker Chung is a sterling example of what it means to be a Space-Trucker, but in all fairness, there’s a dark side to the business. What isn’t publicized is the high rate of turnover among Space-Truckers. Some go mad from the experience of being alone among the stars, while others simply refuse to go back out after their run. Others depart from one place never to arrive at their intended destination.

Figure 1.3 – Space-Trucking is dangerous business

Figure 1.3 – Space-Trucking is dangerous business

Sure, computers can help, and other technologies also contribute to help make Space-Trucking safe and dependable. However, no amount of hardware or software compares to the wetware of the human mind when it comes to dealing with unanticipated situations, and that’s why Space-Truckers need to be behind the wheel of their Space-Rigs.

Before any space wheels can hit the space pavement, our driver needs to know where to go. Space-Dispatch is here to help with Route Planning services, and with their detailed orbital and launch simulation, different potential routes to the cargo’s destination can be evaluated and tried without risk to the Space-Trucker.

Figure 1.4 – Planning a route involves timing the launch as well as properly aiming it. The left-side bar controls the launch impulse – higher is faster

Figure 1.4 – Planning a route involves timing the launch as well as properly aiming it. The left-side bar controls the launch impulse – higher is faster

Despite the risks, the potential rewards are quite high. Completing a Space-Haul has a variable payout for the Space-Trucker, with space-bucks being awarded or demerited based on the driver’s performance in the field. Factors from the simulated route include the total transit time, how much fuel (launch force) is consumed, and the total distance traveled.

Figure 1.5 – Space-Trucking pays well when things go well

Figure 1.5 – Space-Trucking pays well when things go well

Many different obstacles can be encountered, and no two routes are the same, but the scoring factors ensure that when it comes to comparing runs, the High Scores board is the ultimate arbiter of the G.O.A.T Space-Truckers.

Note

G.O.A.T. is not referring to any animal in this context. The Greatest of All Time Space-Truckers are a select and elite group – show proper respect!

Timing is of the essence in Space-Trucking, but so is safety. By being mindful of the latter in service of the former, the Space-Trucker stands the best chance of completing their Space-Haul and getting the opportunity to spend their payday on the Space-Beach.

Never forget, Space-Trucker – the cold, hard equations of planetary motion have no concern for whether you’ve got enough air to breathe or heat to stay warm. Keep your slide rule handy in case of instrument failure and go forth to find your fortune slinging cargo!

Figure 1.6 – Recovered image of a “Space-Trucker” and their “Space-Rig.”  The Space-Trucker is the small figure in the foreground

Figure 1.6 – Recovered image of a “Space-Trucker” and their “Space-Rig.” The Space-Trucker is the small figure in the foreground

END TRANSMISSION

The life of a Space-Trucker certainly must be full of glamorous riches and perilous travels for those folks to send a recruitment leaflet all that distance! Stepping back to the real world is hard, but it’s important that we break down the various elements of how Space-Truckers is designed and put together. Ideally, as you progress through this book, you’ll have this foundation to help you stay grounded with where everything goes and fits together.

 

Space-Truckers: The Video Game Design

The basic idea behind Space-Truckers is simple: get stuff from Point A to Point B, in spaaace! (It’s not required to draw out that last word, but it helps set the mood.) As a game, it is separated into several distinct phases or states:

  • Landing (Home) Screen
  • Splash Screen
  • Menus (inc. High Scores)
  • Route Planning
  • Driving + Scoring

Each of these screens (used as a synonym for “state” here) will be established, then later enhanced over the course of this book along with an underlying application to support and coordinate between them.

Landing

This is the first thing that a player sees when they navigate to space-truckers.com (or the beta testing site, dev.space-truckers.com). It’s an HTML page with a simple Call to Action: “Launch.” Under the hood, however, the HTML page is the host for the main application canvas – the WebGL context onto which all the rendered outputs are painted. It is responsible for loading the packaged web application as well as registration of a Service Worker (see Chapter 13, Converting the Application to a PWA) to manage and pre-fetch assets. As the DOM host, it provides access to the web browser and through it the host machine’s resources, such as the ability to play sound or read input from gamepads or VR hardware. Learn more about this in Chapter 3, Establishing the Development Workflow.

Splash Screen

In music and comedy, a warm-up act precedes the main headline performance as a way to put audiences into a particular frame of mind or mood. After all, it’s much easier to crank things up past 10 on the volume dial when you’re already at 7! The Space-Truckers Splash Screen serves that purpose, as well as giving us an opportunity to showcase the underlying framework and proclaim that this game is Powered by Babylon.js. Once the short, animated content completes, the application enters “attract mode” to entice players to continue.

Menus

The transportation hub of the game, the Main Menu, is where players will start a new game, view high scores, exit back to the landing page, and potentially do more. Sound effects and an animated selection icon bring a bit of motion to a twinkling background. The menu system is initially covered in Space-Truckers: The Main Menu section of Chapter 4, Creating the Application.

Route Planning

One of the two main game phases, the Route Planning Simulation, is where players become content creators. Using a top-down map view, drivers plan their route before embarking on their journey. From an initial starting orbit close to the inner-most planet, players must balance how much launch force is used with aiming and timing to put the simulated cargo on a path to the destination planet. Once launched, the cargo is entirely at the mercy of gravity and Sir Isaac Newton. Pro tip: aim ahead of where you want to end up but be sure to account for the pull of the sun. Because it is a simulation of a route, there are no consequences for failure – the player is free to try as many times as they want to find the perfect route to drive in the next phase.

Driving and Scoring

After planning out the desired route, it’s time for players to then take the wheel and guide their Space-Truck through the transit corridor while avoiding collision with the random events that have been recorded during the route planning phase. The player’s unit drifts in free-fall, so velocity accrued in any given direction will remain unless later canceled out by opposing acceleration. Collision results in damage, and with enough damage, the truck and its cargo are destroyed.

Figure 1.7 – Collisions during the driving phase have consequences

Figure 1.7 – Collisions during the driving phase have consequences

On a brighter note, completing the course results in the player’s score being calculated. Several different factors contribute to the overall total final score. The length of the route, the time it took the simulation to complete the route versus the time the player took, and the initial launch velocity in route planning are all some of the factors involved in scoring. If a player’s score is high enough, then it will displace one of the previous high score holders to place the player’s selected initials into the hall of legends.

This is the game in a nutshell. As with any such high-level overview, it is necessarily lacking in some detail, but it provides a holistic picture of what we’re going to be developing over the course of this book. To get into more detail, we’re going to need to first get an understanding of where we can find those details as well as where and how to pick up supporting context in the GitHub repository for Space-Truckers.

 

Space-Truckers: The Repository

Exploration is an important learning tactic for the discovery of new knowledge. Its converse, exploitation, is an equally important tactic used to convert passing knowledge into actionable skills. The key to maximizing learning is the proper application of each type of learning at the appropriate level and time. With tight iterative exchanges between the two, it is possible to learn a lot in a little amount of time.

Our journey has many stops and signposts along the way to help assist and guide us toward our destination, and in the spirit of maximizing learning, each chapter represents an evolution toward our goal that includes live, runnable examples (exploration) along with the exact source code for the application at that point of the journey.

Figure 1.8 – View the application source in context with the stage of your journey

Figure 1.8 – View the application source in context with the stage of your journey

We accomplish this in a simple fashion via the use of Git branches – one for each chapter involving the application code. In addition, each chapter may have one or more Playground snippets (see Chapter 2, Ramping up on Babylon.js, for more on the Playground) specific to the content covered in that chapter. Snippets are neat in a lot of ways and one of those is that they can have multiple revisions. Toggling between different revisions of a snippet is a great way to visually see how an example has evolved and can help bring insights as to why a particular piece of code behaves as it does.

Maybe things were going OK but then you’ve found yourself stuck on something that you just can’t figure out. That’s OK too – there are places you can go for help! Create a post or add to an existing one in the Discussions board over at https://github.com/jelster/space-truckers/discussions for questions, comments, or concerns about content in the repository and/or book. Questions more general to BJS can be posted over at the BJS community forums – https://forum.babylonjs.com. Creating an account for both GitHub and the BJS Forums can be relatively quick and painless.

Tip

If you are planning to create both a BJS Forum and a GitHub account login, save yourself half the effort by signing up for GH first. Then, when you create your forum account, you can select the Login With GitHub option, supplying the information for your newly created GH account.

The Space-Truckers repository has more than just the source code and discussions, though. It also hosts the Issue Tracker for the game (https://github.com/jelster/space-truckers/issues), which is where people can request a new feature or file a bug report – it’s also where folks looking to contribute to the project can peek to find something suitable to their abilities.

Tip

Another pro-tip offered pro rata via the cost of this book: Scan through issues with the labels good-first-issue and needs-help. Those are ones the repository’s maintainers either need assistance with or feel that the issue represents a gentle introduction to the code base.

Community contributions are what Open-Source Software (OSS) is all about, but because they are largely volunteer-driven, there’s always more work than there are people that can get that work done. Consequently, most maintainers are thrilled whenever somebody submits a Pull Request – a set of changes to be incorporated into the code base – to the project that resolves an existing issue!

Tip

Getting tired of these yet? Fair enough. Final tip: Even projects like BJS with many maintainers working full time on it have this problem. The maintainers might not be having to scrounge donations to keep servers on, but they do have to scrounge for the time to accomplish everything that we want them to!

It can be difficult to synthesize and learn new things when it feels like you’re in drinking all the newness through a firehose. That’s why the Space-Truckers code base is branched by chapter. Though an individual chapter won’t necessarily resemble the current, final game as represented in the main or develop branches (production and beta environments, respectively), each branch has as much complexity as it needs to have for that point in the book and no more. To put it differently, the evolution of the application will mirror the evolution of our journey as it unfolds.

 

Summary

The next thirteen chapters each represent their own signpost denoting the progress of our journey, and there is much yet to see and accomplish. Pulling onto the Space-Highway, it can appear like the space-road ahead is stretching out toward infinity. The truth is every road seems that way at the start of a trip. By keeping the focus on what’s immediately ahead, the infinite can become finite, and overwhelming complexity becomes manageable tasks.

Much like this book is separated into sections and chapters, Space-Truckers is separated into distinct phases or states. The Landing Page is the launchpad (pun intended) for starting the game, while the Splash Screen prepares the audience and sets the mood. Meanwhile, the Main Menu Screen serves as a navigation hub between the main gameplay states and the others.

There are two(ish) phases to the gameplay. Route Planning is where players use an orbital mechanics simulation to plot a course for their Space-Cargo to get from the origin to the destination planets. The direction and force of the launch are set by the player prior to launch, with the timing of the launch also a major factor in how players dictate their route.

Having planned a route, the next game phase sees that route being used to create a tunnel filled with obstacles (random encounters) that the player now must navigate their Space-Truck through to reach the end point. Time matters, but so does bringing the cargo to its destination in as good a condition as possible. Once the destination has been reached, a third, pseudo-game phase enters the stage.

Scoring is done using several factors that will be outlined in detail as part of Chapter 9, Calculating and Displaying Scoring Results. Players’ decisions from Route Planning impact the final scores in multiple ways ranging from time goals to fuel costs. Only the top scores get persisted into the High Score Screen, a feature available in both the web and PWA versions of the application.

The place where all the work around Space-Truckers is tracked and managed is in Space-Truckers: The GitHub Repository. Additionally, each chapter of the book (with a few exceptions) has its own branch in the source code. This allows you to view the state of the overall application in context with the content of the corresponding chapter. Additional assistance can be found by posting in either Space-Truckers: The Discussion Boards or on the BJS official community forums.

Next, we’ll start by gradually building some momentum through a back-to-basics review of the BJS framework and ecosystem. We’ll look at some of the tools, resources, and techniques and if necessary (re)introduce ourselves to how rendering in BJS works. We’ll learn about the Playground and begin the process of building our application by creating a simple loading animation. Buckle up, Space-Trucker – we’re hitting the road!

About the Author
  • Josh Elster

    Josh Elster spends most of his days working as a software engineering lead for a technology startup and his nights patrolling the BabylonJS forums and working on various side-projects. Unlike Bruce Wayne, however, he did not have a traumatic childhood incident involving bats. From his home in the Windy City of Chicago, Josh likes to spend time outdoors, particularly working with wood in his woodshop when the weather indicates, and gaming or reading when it doesn’t. He has a website named liquidelectron and can also be found on LinkedIn and Twitter

    Browse publications by this author
Going the Distance with Babylon.js
Unlock this book and the full library FREE for 7 days
Start now