More fun with constexpr

Continuing from my earlier post, here’s another look at how we can abuse the compiler and C++11’s compile-time abilities. This one might even be useful!

The Problem

Trigonometry functions are common in a lot of programming. On modern hardware, they’re usually highly optimized, too. But C++ developers are taught to use the compiler as much as possible. That’s why we have templates and constexpr, after all. So, can we do trig calculations this way?

The answer, of course, is “yes”. (If it wasn’t, then this post wouldn’t exist.) We’ll start with the cosine function, since it’s probably the easiest to implement. One way to define the cosine function is as an infinite series that I don’t really want to try to recreate in math notation here. As it turns out, that definition is fairly easily convertible to a recursive function that can be evaluated at compile-time.

The Code

template <int Iterations = 10>
constexpr double cosine (double theta)
{
    return (power(-1, Iterations) * power(theta, 2 * Iterations)) /
            static_cast<double>(factorial(2ull * Iterations))
        + cosine<Iterations-1>(theta);
}

template <>
constexpr double cosine<0> (double theta)
{
    return 1.0;
}

Since the Taylor series is an infinite one, we obviously can’t run the whole thing. So we approximate. I’ve decided on a default of 10 iterations, but the function, you should note, actually calculates the series “in reverse”. The base (i.e., last) case, when Iterations == 0, is the first term in the series expansion. It’s okay, though. The algorithm still works this way, although it might look a little weird.

Also, note that this cosine function uses two other constexpr functions. The first, power(), is our creation from last time, slightly renamed. The second is a typical factorial function. (It’s a good thing every single constexpr tutorial uses this one, otherwise I’d have to write it myself!) factorial takes an integer and returns another one, so I used an explicit cast to double. You could just change the definition of factorial, though, if you don’t mind the possible loss of precision. You’d probably want to template the whole thing on the type, too, instead of only using doubles.

The other trig functions can, for the most part, work off this base. The sine series raises the angle to the power of 2n+1 instead of 2n (and takes the factorial of 2n+1, as well), but it’s otherwise the same. Tangent, as you know, is sine divided by cosine. The reciprocals (secant, cosecant, cotangent) are trivial. You’d also need conversions between degrees and radians (this function uses radians), but that’s so easy you can do it in your sleep.

In a real application, you might want to combine this with lookup tables or something, especially because of rounding errors and the limited precision of floating-point numbers.

Now What?

If I can find any more constexpr contortions, I’ll definitely be making more posts. There’s still so much of the standard math library left, you know.

Phaser 2.4 released

A while back I mentioned that I thought Phaser was a good choice for beginners of game development. It’s well-supported, it’s popular on browsers and mobile devices, and it uses the current most popular language: JavaScript.

Now, the guys behind Phaser have released version 2.4, and it has quite a few changes and updates. Most people will be gushing over the support for boned animation and video, but there are a few nuggets hidden in the changelog that might be just as useful. Let’s see what we can find, eh?

  • Phaser.Text no longer extends PIXI.Text but replaces it entirely. Phaser.Text now natively extends a Phaser Sprite, meaning it can be enabled for physics, damaged, etc.

On the surface, not a huge change, mostly just back-end stuff. But look at the second half of the entry: text objects are now sprites in their own right. That actually makes the code for a lot of games much easier, simply because we can use all the sprite methods on text. Think of, say, a word puzzle, where every word (or letter) can be made into its own sprite.

  • Mouse.button and MSPointer.button have been deprecated and are no longer set (they remain at -1). They never supported complex button events such as holding down 2 buttons and releasing just one, or any buttons other than left and right. They have been replaced with the far more robust and accurate Pointer DeviceButton properties such as Pointer.leftButton, Pointer.rightButton and so on.

This (and a handful of entries following it) is another step towards “unifying” control schemes. It’s annoying to have to write separate code to handle the mouse and a touchscreen. Now we don’t have to. Of course, you still need to compensate for the fact that a mouse can have nearly pixel-perfect accuracy, whereas fingers are lucky to get within about a centimeter of their target.

  • Added support for the Creature Automated Animation Tool. You can now create a Phaser.Creature object which uses json data and a texture atlas for the animations. Creature is a powerful animation tool, similar to Spriter or Spine. It is currently limited to WebGL games only, but the new libs should prove a solid starting point for anyone wanting to incorporate Creature animations into their games.

This is the one everybody’s talking about. To be honest, it doesn’t intrigue me as much. Creature is just one commercial, proprietary tool among many. Show me an open standard for 2D bones, and then I’ll get excited.

  • Loader.video allows you to load a video file into Phaser. It works in the same way as Loader.audio, allowing you to pass an array of video files – and it will load the first one the device is capable of playing back. You can optionally load the video via xhr where the video data is converted to a Blob upon successful load.

Video is cool, no doubt about it. But the whole field of in-browser video is a disaster area. Format support, patents, DRM, it’s all enough to make somebody swear off the whole thing forever. Still, if you can figure out a way to use it safely and easily, more power to you. Maybe it’ll lead to a revival of FMV games.

  • Text.setTextBounds is a rectangular region that allows you to align your text within it, regardless of the number of lines of text or position within the world. [ed: I removed the example, shout-out, and issue number]

More text rendering goodness. I can’t complain. This and other additions simplify the task of making a text-heavy game, something most game engines (not only HTML5, and not only free) make absurdly difficult.

  • Keyboard.addKeys is a practical way to create an object containing user selected hotkeys. [ed: Same removals here.]

Better keyboard support is a good thing in any engine, especially as so many are trying to forget that a physical keyboard even exists. And an easier way to support hotkeys can never be bad, because they’re one of the most annoying parts of a control scheme.

  • All Game Objects and Groups have a new boolean property called pendingDestroy. If you set this to true then the object will automatically destroy itself in the next logic update, rather than immediately. [ed: Removed use case and call-out.]

Godot has this same thing (as queue_free()), and it’s very helpful there. In a language full of callbacks (like JS), it’s even more necessary. Again, this isn’t something you want to scream out from the rooftop, but it’s a subtle change that eliminates a whole class of coding errors. Who could ever argue with that?

  • All Signals now have the ability to carry extra custom arguments with them, which are passed on to the callback you define after any internal arguments. [ed: Same removals here.]

A good customization point that’s never going to be important enough to mention in a press release. But it’s nice to have, and it simplifies some common tasks.

  • Phaser.Create is a new class that allows you to dynamically generate sprite textures from an array of pixel data, without needing any external files. We’ll continue to improve this over the coming releases, but for now please see the new examples showing how to use it.

Depending on how this plays out, it could be a great addition to an already excellent engine. A lot of designers absolutely hate generated textures, but I like them. Get some good noise algorithms in there, and you could do some wonderful things.


There’s a lot more in there, and I do mean a lot. And Phaser 3 should be coming within the next year or so, although release dates always have a tendency to…slip. But this 2.4 release does help cement Phaser as the forerunner for HTML5 game development. For coders rather than designers, there’s really not a better option, and I’ll continue to recommend Phaser for anybody that wants to get started with game coding. Unity’s great and all, but it’s a lot more complicated than popping open a text editor and a browser, you know?

A simple constexpr power function (C++)

Since C++11, programmers have been given the power of compile-time calculation without the hassles of template metaprogramming. (And they are hassles, believe me.) The canonical example is a factorial function completely evaluated by the compiler, but here’s another, different use, one that has much more utility.

The Power Function

It’s a sad fact that C++ has no power operator. Sure, we have the std::pow function inherited from C, but that works at runtime, which means we can’t use it in template arguments. Most notably, we can’t say something like array<int, pow(4,4)>. In other words, we aren’t allowed to use a power function when declaring the size of a C++11 array. Most users, of course, will never need it, but you never know when it might come in handy, so here it is:

template <typename T>
constexpr T ipow(T num, unsigned int pow)
{
    return (pow >= sizeof(unsigned int)*8) ? 0 :
        pow == 0 ? 1 : num * ipow(num, pow-1);
}

There are a few caveats. First, it’s (obviously) a template, so you can use it on integers, doubles, or anything else that has a binary operator* (i.e., the arithmetic one, not the pointer one). All it does is the classic “raise to a power” algorithm: repeatedly multiply a number by itself. Like the typical factorial function, it’s really written in a function mode. It even has a proper tail call, if you’re into that sort of thing. Incidentally, that’s why the second argument (the power to raise to) must be an unsigned int: you can’t use the elementary-school method with fractional powers, and raising an integer to a negative power gives you a fraction, which means that there could be type issues.

The second thing to notice is that it could use some better error handling. I put a check in to keep somebody from calling it with some huge power like 1,000,000, but all it does is return 0. It should probably throw an exception, instead. Maybe I’ll change it in version 2.

Last, this clearly won’t be useful for a class where “raise to a power” isn’t the same thing as “multiply by itself over and over”. But if I had to guess, I’d say that there aren’t too many places where you’d want to raise that kind of object to a power at compile-time. I’d love to see a counterexample, though.

Anyway, that’s all for this time. I intend to expand on this idea (complex arithmetic at compile-time) later, so I’ll see you then.

Introduction to ES6 Modules for Game Programmers

As an application (be it a game or anything else) grows, so does the need for some sort of organization. Also, all but the simplest programs will require the use of some sort of additional libraries. For both of these reasons, just about every programming language meant for serious use has a way to separate code into logical, self-contained blocks. Even lowly C has its header files, but more modern languages can do more.

JavaScript, however, used to be sorely lacking in this department. Sure, you can load additional scripts in a web page, and jQuery (to name one example) managed an entire plugin architecture using DOM onload events. But everyone recognized that this wasn’t enough, and thus modules were born.

The problem is, they weren’t a part of the JavaScript “core”, so there was no standard way of making or using a module. Node made its own module system based off the CommonJS spec (later used by Browserify), while Require.js championed a slightly different style called AMD. In general, server-side and other “app”-style JS used Node’s modules, since they were already using Node itself, while purely browser-based libraries went with AMD. As with any case where there are two competing standards, developers are left having to learn both of them.

Now, with ES6, all that can change. Modules are now a core part of the language. Once browsers fully support them, you can use them anywhere. (Babel can convert ES6 modules into AMD or CommonJS, though, if you want to use modules right now.) And this is a case where you’ll definitely want to, no matter what you’re writing.

Using Modules

Most of the discussions out there focus on writing modules, rather than using them. But game developers, in particular, are going to be more likely to use somebody else’s module first, so I’m starting there.

The import keyword is your gateway to modularity. If you’ve ever used require() in Node, you’re halfway there, but you’ve still got more to learn. The idea is pretty simple, though. Let’s say that we’re using some made-up game library that’s fully modularized, so that all its classes (because it’s all ES6, see?) are in their own module files. Well, we can do this:

import Vec2d from "lib/vector2d";

Now Vec2d is available for us to use in the rest of that script, and it will be whatever the vector2d module exported. Presumably, that would be a class or a function that created a 2D vector.

That’s the most basic import. For modules that export a single value (class, function, or even a constant), it’s all you have to do. In fact, the way the standard was made, it’s actually the preferred way of doing things. But it’s not the only way. What if we have a module that gives us multiple exports?

import {normalize, dotProduct} from "lib/vector2d";

That gives us names for two functions that might be defined (and exported) in our hypothetical vector2d module. Of course, we can combine these two:

import Vec2d, {normalize, dotProduct} from "lib/vector2d";

Here, the default export (see below) is assigned to the name Vec2d, while the braces indicate exports that we’re “picking” from the module. If we don’t like the names the module gives us, no problem:

import Vec2d, {normalize, dotProduct as dotP} from "lib/vector2d";

Finally, if we have a module that has a lot of exports (maybe something like jQuery), we can use a “wildcard” import that brings in the whole module as an object:

import * as $ from "lib/jquery";

We do have to name the object we’re importing into. (I used the traditional $ for jQuery.) After we use this import, anything the module exported with a name will be available as a property on the $ object.

Note that all importing is done statically, so you can’t “conditionally” import like this. (This is one downside to ES6 modules compared to earlier attempts like Node’s.) For that, you need to use the new Module Loader API, which would look something like AMD:

System.import("lib/jquery")
    .then(function($) {
        // Use jquery module as $, just like always
    });

Creating Modules

Eventually, you’ll want to make your own modules. For a game, you might be using a classical OO approach, where all your game entities (enemies, powerups, etc.) are ES6 classes, each in their own file. Like we did above, we’ll start with the simplest case, where your module only has one value, particularly a class.

/* enemy.js */
export default class {
    // Class definition...
};

That’s all there is to it. export default is the magic phrase that tells your JS interpreter that you’re defining a module and that you want it to export a single value. That value could be anything: class, function, constant, or even another module. And, when you want to use your enemy, all you have to do is import it like we did earlier.

If you want a module with more than one export (maybe a library of independent functions), then you can use a syntax that’s almost the reverse of that for importing multiple values:

/* utils.js */
export function log(msg) {
    console.log(msg);
}

export function foo(bar) {
    // Some other function
}

export const MAX_FPS = 60;  // TODO: Lower to 30 for console builds

All of these will be exported, and they can be imported using the “braces” or “wildcard” versions of import. (Since there’s no default export, these are, in fact, the only two ways to use the module. A simple import utils from "utils"; wouldn’t help us here.)

If you don’t like writing export everywhere in a module like this, you have an alternative. Instead, you can write the module as you normally would, then add an export declaration at the end. This declaration consists of export followed by the name of each expression you’re exporting, all of them put in braces, like an object literal. In other words, like this:

/* utils2.js */
function log(msg) {
    console.log(msg);
}

function foo(bar) {
    // Some other function
}

const MAX_FPS = 60; // TODO: Lower to 30 for console builds

export {log, foo, MAX_FPS};

The main advantage of this style is that you can export a function (or whatever) under a different name, using as like we can when importing. So, for example, we could instead write the last line as export {log as debug, foo, MAX_FPS};.

In Closing

So modules are good, and ES6 modules make JavaScript even better. Combined with classes, we now have a language that makes writing programs (including games) much easier. Once support for modules becomes widespread in browsers, all JS game developers will reap the benefits that “native” devs already enjoy.

Thoughts on ES6

ES6 is out, and the world will never be the same. Or something like that. JavaScript won’t be the same, at least once the browsers finish implementing the new standard. Of course, by that time, ES7 will be completed. It’s just like every other standardized language. Almost no compilers fully support C++14, even in 2015, and there will certainly be holes in their coverage two years from now, when C++17 (hopefully) arrives. C# and Java programmers are lucky, since their releases are dictated by the languages’ owners, who don’t have to worry about compatibility. The price of a standard, huh?

Anyway, ES6 does bring a lot to the table. It’s almost a total overhaul of JavaScript, in my opinion, and most of it looks to be for the better. New idioms and patterns will arise over the coming years. Eventually, we may even start talking about “Modern JavaScript” the way we do “Modern C++” or “Modern Perl”, indicating that the “old” way of thinking is antiquated, deprecated. The new JS coder in 2020 might wonder why we ever did half the things we did, the same way kids today wonder how anyone got by with only 4 MB of memory or a 250 MB hard drive (like my first PC).

Babel has an overview of the new features of ES6, so I won’t repeat them here. I will offer my opinions on them, though.

Classes and Object Literals

I already did a post on classes, with a focus on using them in games. But they’re useful everywhere, especially as so many JavaScript programmers come in from languages with a more “traditional” approach to objects. Even for veterans, they come in handy. We no longer have to reinvent the wheel or use an external library for simple inheritance. That’s a good thing.

The enhancements to object literals are nice, too. Mostly, I like the support for prototype objects, methods, and super. Those will give a big boost to the places where we don’t use classes. The shorthand assignments are pure sugar, but that’s really par for the course in ES6: lots of syntactic conveniences to help us do the things we were already doing.

Modules

I will do a post on modules for game development, I promise. For now, I’d like to say that I like the idea of modules, though I’m not totally sold on their implementation and syntax. I get why the standards people did it the way they did, but it feels odd, especially as someone who has been using CommonJS and AMD modules for a couple of years.

No matter what you think of them, modules will be one of the defining points of ES6. Once modules become widespread, Browserify becomes almost obsolete, RequireJS entirely so. The old pattern of adding a property to the global window goes…out the window. (Sorry.) ES6 modules are a little more restrictive than those of Node, but I’d start looking into them as soon as the browsers start supporting them.

Promises

Async programming is the hot thing right now, and promises are ES6’s answer. It’s not full on threading, and it’s distinct from Web Workers, but this could be another area to watch. Having a language-supplied async system will mean that everybody can use it, just like C++11’s threads and futures. Once people can use something, they will use it.

Promises, I think, will definitely come into their own for AJAX-type uses. If JavaScript ever gets truly big for desktop apps, then event-driven programming will become even more necessary, and that’s another place I see promises becoming important. Games will probably make use of them, too, if they don’t cause to much of a hit to speed.

Generators and Iterators

Both of these really help a lot of programming styles. (Comprehensions do, too, but they were pushed back to ES7.) Iterators finally give us an easy way of looping over an array’s values, something I’ve longed for. They also work for custom objects, so we can make our own collections and other nifty things.

You might recognize generators from Python. (That’s where I know them from.) When you use them, it will most likely be for making your own iterable objects. They’ll also be handy for async programming and coroutines, if they’re anything like their Python counterparts.

Syntactic Sugar

A lot of additions to ES6 are purely for aesthetic purposes, so I’ll lump them all together here, in the same order as Babel’s “Learn ES2015” page that I linked above.

  • Arrows: Every JavaScript clone (CoffeeScript, et al.) has a shortcut for function literals, so there’s no reason not to put one in the core language. ES6 uses the “fat” arrow =>, which stands out. I like that, and I’ll be using it as soon as possible, especially for lambda-like functions. The only gotcha here? Arrow functions don’t get their own this, so watch out for that.

  • Template Strings: String interpolation using ${}. Took long enough. This will save pinkies everywhere from over-stretching. Anyway, there’s nothing much to complain about here. It’s pretty much the same thing as PHP, and everybody likes that. Oh, wait…

  • Destructuring: One of those ideas where you go, “Why didn’t they think of it sooner?”

  • Function Parameters: All these seem to be meant to get rid of any use for arguments, which is probably a good thing. Default parameters were sorely needed, and “rest” parameters will mean one more way to prevent off-by-one errors. My advice? Start using these ASAP.

  • let & const: Everybody complains about JavaScript’s scoping rules. let is the answer to those complaints. It gives you block-scoped variables, just like you know from C, C++, Java, and C#. var is still there, though, as it should be. For newer JS coders coming from other languages, I’d use let everywhere to start. const gives you, well, constants. Those are nice, but module exports remove one reason for constants, so I don’t see const getting quite as much use.

  • Binary & Octal Literals: Uh, yeah, sure. I honestly don’t know how much use these are in any higher-level language nowadays. But they don’t hurt me just by being there, so I’m not complaining.

Library Additions

This is kind of an “everything else” category. ES6 adds quite a bit to the standard library. Everything that I don’t feel is big enough to warrant its own section goes here, again in the order shown on “Learn ES2015”.

  • Unicode: It’s about time. Not just the Unicode literal strings, but the String and RegExp support for higher characters. For anyone working with Unicode, ES6 is a godsend. Especially if you’re doing anything with emoji, like, say, making a language that uses them.

  • Maps and Sets: If these turn out to be more efficient than plain objects, then they’ll be perfect; otherwise, I don’t think they are terribly important. In fact, they’re not that hard to make yourself, and it’s a good programming exercise. WeakMap and WeakSet are more specialized; if you need them, then you know you need them, and you probably won’t care about raw performance.

  • Proxies: These are going to be bigger on the server side, I think. Testing will get a big boost, too, but I don’t see proxies being a must-have feature in the browser. I’d love to be proven wrong, though.

  • Symbols: Library makers might like symbols. With the exception of the builtins, though, some of us might not even notice they’re there. Still, they could be a performance boost if they’re faster than strings as property keys.

  • Subclassing: Builtin objects like Array and Date can be subclassed in ES6. I’m not sure how I feel on that. On the plus side, it’s good for consistency and for the times when you really do need a custom array that acts like the real thing. However, I can see this being overused at first.

  • New APIs: The new builtin methods are all welcome additions. The Array stuff, particularly, is going to be helpful. Math.imul() and friends will speed up low-level tasks, too. And the new methods for String (like startsWith()) should have already been there years ago. (Of all the ES6 features, these are the most widely implemented, so you might be able to use them now.)

  • Reflection: Reflection is always a cool feature, but it almost cries out to be overused and misused. Time will tell.

Conclusions

ES6 has a lot of new, exciting features, but it’ll take a while before we can use them everywhere. Still, I think there’s enough in there to get started learning right now. But there are going to be a lot of projects that will soon become needless. Well, that’s the future for you, and what a bright future it is. One thing’s for sure: JavaScript will never be the same.

Introduction to ES6 Classes for Game Programmers

If you’ve used JavaScript for game programming, you probably already know some of its shortcomings. One of those is its object system. Where most languages that have objects are class-based (think C++, Java, etc.), JavaScript is unusual in that it’s prototype-based. If you have experience with the language, you know this already, of course. And you know that the syntax can leave a lot to be desired, especially if you come from a background in, say, any other language. (Well, any class-based language, at least. If you’re used to something like Lisp or Haskell, then nothing will surprise you.)

With the newest standard, ES6, that’s going to change. It’s supposed to come out by the end of this month, and maybe that’s true. I’m writing this on June 15th, so it might even be released before this post goes up. If that’s the case, great! (I still remember when C++11 was codenamed C++0x, so I remain skeptical.) Anyway, some of the new features of ES6 are incredibly useful for all developers, but we’ll start with classes, because they’re simple yet powerful, and game development has always been one of the main uses of object-oriented programming. (EDIT 6/18: ES6 is now out! I’m amazed, and I’m happy to admit that I was wrong. Even though the release happened between writing this and posting it, I won’t remove what I already said.)

(By the way, most browsers don’t support much of ES6 yet, and even Node.js support is spotty. You’ll likely need to use a transformer like Babel to turn your ES6 code into something usable under the current standard, ES5.)

Basic Syntax

Let’s take a look at a little class that we can use to represent an enemy in a game. In ES6, it might look something like this:

class Enemy {
    constructor(id, name) {
        // Some properties that are passed into the constructor
        this.id = id;
        this.name = name;

        // A property we can define ourselves
        this.health = 100;
    }

    doAI() {
        /* Do some AI work here */
    }

    kill() {
        /* Play a death animation or something */
    }

    hit(damage) {
        this.health -= damage;
        if (this.health <= 0) {
            this.kill();
        }
    }
}

If you’ve ever worked with Java, C++, C#, ActionScript, or any other language like that, then the syntax will be familiar. Inside the class definition, you can define methods, both instance methods (like all of those here) and static methods. Instance methods are basically the same as the prototype methods already in JavaScript. You call them on an instance of an object, and they can use that object as this. Static methods don’t require an instance of the class; they’re called on the class itself, like the functions of the Math object.

Using this class is as easy as any object constructor. var myEnemy = new Enemy(0, 'myEnemy'); is exactly the same as what you’d use if we defined Enemy in the traditional JS way, defining methods on the prototype and so on. That’s the beauty (if you want to call it that) of ES6 classes: deep down, they’re the same thing as before, but prettier, like CoffeeScript and Typescript claim to be.

constructor is a special method. (I wonder what it does…), but you can define any other method you like. You can also use get and set before method names, just like with the object literal syntax. Static methods are prefixed with static. And that’s pretty much it.

Inheritance

If ES6 classes could just do that, they’d be a pretty good bit of syntactic sugar, but they’d definitely be missing something. Subclassing (AKA inheritance) is that something. Like their counterparts in other languages, ES6 classes can derive from another class, adding or redefining methods and properties. Taking our Enemy class from above, we can make a couple of different enemies using subclasses:

class ToughEnemy extends Enemy {
    constructor(id, name) {
        super(id, name);

        this.health = 200;
    }
}

class BossEnemy extends ToughEnemy {
    constructor(id, name) {
        super(id, name);

        this.lives = 3;
    }

    kill() {
        if (this.lives > 0) {
            this.lives--;
            this.health = 200;

            /* say something cheesy
            e.g., "Ha! You thought I would go down that easy?"
            and play a regeneration animation */
        } else {
            // All lives are gone, so he's really dead
            super.kill();
    }
}

Now we have two new classes. ToughEnemy is a generic bad guy with double health. There’s not much to change for him, but it shows the super keyword that we can use to call methods of the superclass. In the constructor, you can use it by itself to call the superclass constructor. Actually, you have to. Otherwise, you can’t use this anywhere in the derived class’ constructor. Since we want to change the this.health property, we do call super, forwarding the constructor parameters to it, which also means we don’t have to deal with them.

For BossEnemy, we further subclass ToughEnemy, but with a little added logic. First, we give him a property this.lives, set to 3. Then, we change his kill() method as you can see above. If he goes down to 0 health, he loses a life, but he goes back to full health. That continues until he’s out of lives, when we call the superclass kill() method. Since we didn’t define one for ToughEnemy, the call goes up another level, to Enemy, which does have kill().

So, to make a subclass, define a class as usual, but add extends and the name of the base class after your derived class’ name. Everything else is the same, except for the caveat about super in the constructor. You can change methods to your heart’s content, and any that you leave out will stay the same as they were in the base class. Just like any other OO language. Like it should be.

The only downside (and a lot of people wouldn’t see it as such) is that you only get single inheritance, meaning you can only derive from one base class. That’s okay for JS, since we didn’t have anything else to begin with. And Java doesn’t have multiple inheritance, nor does C#. C++ and Python do, but it takes a lot of extra work on the programmer’s part to use it well. Basically, once you truly need multiple inheritance, you’ll know how to fake it, no matter what language you’re using.

For Games

Since ES6 classes are just a fancier way of writing JS prototypes, you can use them wherever you’d use those: pretty much anywhere. And, due to the way they’re defined, you can subclass “traditional” JS objects by extending a constructor. This includes builtins like Array (but not Math, as it’s not a constructor). If you’re using a game library like Phaser, you can extend its objects with classes, too. Basically, wherever you’d already use objects and prototypes, classes fit right in.

Compatibility

ES6 is new, and not everything supports it. According to this compatibility table, nothing actually has full support for classes yet. Firefox 39 will have just about everything, and Chrome 42 allows classes, but not completely. Internet Explorer, as usual, is hopeless, but Edge has quite a bit of support if you enable “experimental” JavaScript. Safari and iOS are out of the question right now. Realistically, if you want to use ES6 classes at the moment, you’ll need a transformer. But that will change, and the next generation of programmers might wonder why we ever bothered with prototype at all.

Repeatable Random Numbers with xorshift+ (JS)

Like most languages, JavaScript has a random number generator: Math.random(). It’s not the best, but it’s good enough for many purposes, including some we’ve seen before. Like the RNGs of most languages, though, Math.random() has its drawbacks. Of these drawbacks, one is very important for game developers: there’s no way to seed! Why is this bad? That cuts to the very heart of random number generation on computers.

True randomness is hard to come by. On a computer, you have a few ways of creating it, such as noise circuits or measurements of user input. This randomness (entropy) is then converted by code into something usable, such as numbers or bits. On Linux and similar systems, there is a special file, /dev/random, that provides access to the random data. Some programming languages then allow developers to use the data through mechanisms like C++’s std::random_device.

All well and good, right? As long as your source has enough randomness, you can generate all the numbers you need. But, contrary to thermodynamics, a computer’s entropy can run out. When that happens, /dev/random stops working, waiting until it can conjure up enough random bits to meet your needs. Other systems fare no better.

Fortunately for us, games don’t often need true random numbers for gameplay. (Authentication and encryption are a different story.) So we can get away with something that only looks random. That’s good for us, because there are plenty of algorithms out there that can make a convincing string of numbers, including Math.random(). Technically, they aren’t “true” random numbers, and they all have a weakness that can allow someone with enough data to guess the next numbers in the sequence. But that very predictability comes in handy for game development. Starting from a little bit of data (from one number to a few, depending on the algorithm used), we get a whole set of numbers, billions of them or more. That starting data is the seed.

Most languages that I’ve used allow you to set the seed on the RNG. C, for example, has the srand() function, while Python provides random.seed(). But JavaScript doesn’t have this. Instead, the RNG is seeded for you when your program/app/page loads, and it will be different every time. Usually, that’s not a problem.

Sometimes, though, you need the predictable sequence that comes from using a seed. Procedural generation is one notable example. Look at Minecraft: a whole world can be created from a simple string of text. Obviously, there’s randomness injected in the process, but it’s made on-demand. Think how hard it would be to store the whole world after creating it. But, if you only had JavaScript’s RNG, you wouldn’t have much of a choice.

There are better RNG implementations out there. Indeed, many have written JS versions of them. Here’s my attempt at the popular algorithm known as xorshift+.

module.exports = (function() {
    // xorshift128+ requires 128 bits of state (we'll seed later)
    var state = new Uint32Array(4);

    // Scaling factor (2^32) to convert Math.random floats into integers
    var MAXINT_PLUS_1 = Math.pow(2,32)

    // Pre-fill the state array (can later be seeded)
    // This is required because xorshift can't have state of all zero
    for (var i = 0; i < state.length; i++) {
        state[i] = Math.random() * MAXINT_PLUS_1;
    }

    // A saved random number, since we're returning 32-bit numbers
    var saved;

    return {
        // Seeds the internal RNG.
        seed: function(s) {
            if (s === 0 || s == null) {
                // Can't use a zero seed (maybe throw an exception?)
                return;
            }

            // TODO Handle various types of arguments (just numbers/arrays for now)
            if (typeof s === 'number') {
                // Use only the lowest 32 bits right now
                state[0] = s >>> 0;
            } else if (s.constructor && s.constructor.name === 'Uint32Array') {
                for (var i = 0; i < state.length; i++) {
                    if (s[i] !== undefined) {
                        state[i] = s[i];
                    } else {
                        state[i] = 0;
                    }
                }
            }
        },

        // Returns a random float between 0 and 1 (exclusive),
        // with 32 bits of precision.
        random: function() {
            // If we already have a saved number, return it,
            // also clearing it for later use.
            if (saved != null) {
                var temp = saved;
                saved = null;
                return temp / MAXINT_PLUS_1;
            }

            // x = s[0]
            var x = new Uint32Array(2);
            x[0] = state[0];
            x[1] = state[1];

            // y = s[1]
            var y = new Uint32Array(2);
            y[0] = state[2];
            y[1] = state[3];

            // s[0] = y
            state[0] = y[0];
            state[1] = y[1];

            // (a): x ^= x << 23
            var xl23 = new Uint32Array(2);
            xl23[0] = x[0] << 23;
            xl23[1] = (x[1] << 23) & (x[0] >> 11);
            x[0] ^= xl23[0];
            x[1] ^= xl23[1];

            // (b): x ^= x >> 17
            var xr17 = new Uint32Array(2);
            xr17[1] = x[1] >>> 17;
            xr17[0] = (x[0] >>> 17) & (x[1] << 19);
            x[0] ^= xr17[0];
            x[1] ^= xr17[1];

            // (c): x ^= y ^ (y >> 26)
            var yr26 = new Uint32Array(2);
            yr26[1] = y[1] >>> 26;
            yr26[0] = (y[0] >>> 26) & (y[1] << 6);
            x[0] ^= y[0] ^ yr26[0];
            x[1] ^= y[1] ^ yr26[1];

            // s[1] = x
            state[2] = x[0];
            state[3] = x[1];

            // return x + y
            var retval = new Uint32Array(2);
            retval[0] = x[0] + y[0];
            retval[1] = x[1] + y[1] + (retval[0] < x[0]);
            saved = retval[1];
            return retval[0] / MAXINT_PLUS_1;
        }
    };
})();

I’ve written it as a Node.js module, but you can easily adapt it to a browser environment by changing module.exports on line 1 to window.xorshift or whatever you like. Whether it’s attached to the global window (browser) or loaded with require() (Node), the function creates an object with two methods: random() and seed(), both of which are explained below.

This isn’t a perfect implementation, and it does have a limitation that the original doesn’t have. This is because of JavaScript’s number handling, which might best be termed as “special”. JS only really has 64-bit floats for numbers, unless you do even more TypedArray contortions than I did here. So I had to compromise by making the random() function output numbers between 0 and 1 with 32 bits of resolution. Each run of the algorithm creates 64 bits of randomness, so I split that into two numbers, saving the second for the next call to the RNG. Changing the function to return integers instead of floats is easy enough: remove the two divisions by MAXINT_PLUS_1.

The whole reason for making this thing was to have a predictable RNG for JavaScript. That’s what the seed() function does. Pass in a single 32-bit integer or a typed array of them, and it will seed the algorithm using that. (One good way to extend this would be to use a hash such as MD5 to allow strings and other objects. That’s why the “TODO” comment is there.) If you don’t, it will use a few numbers generated from Math.random().

Another benefit of this (or any similar RNG) over the stock implementation is that you can create more than one, each tied to its own seed. This means that, for example, you can have your world generator running off a different sequence than your AI. You would then only have to save the seed for the world RNG, while the AI RNG gets reseeded when you reload the game. This would prevent players from, say, repeatedly reloading to get a good outcome of a battle in a strategy game.

As usual, I didn’t make the algorithm; I only wrote the code in this post. You can use it for whatever purpose you like, but I’m sure there are better implementations out there. I didn’t check, mostly because I wanted to try my hand at writing it first. It’s good practice.

Until next time, have fun!

First Languages for Game Development

If you’re going to make a game, you’ll need to do some programming. Even the best drag-and-drop or building-block environment won’t always be enough. At some point, you’ll have to make something new, something customized for your on game. But there are a lot of options out there. Some of them are easier, some more complex. Which one to choose?

In this post, I’ll offer my opinion on that tough decision. I’ll try to keep my own personal feelings about a language out of it, but I can’t promise anything. Also, I’m admittedly biased against software that costs a lot of money, but I know that not everyone feels the same way, so I’ll bite my tongue. I’ll try to give examples (and links!) of engines or other environments that use each language, too.

No Language At All

Examples: Scratch, Construct2, GameMaker

For a very few cases, especially the situation of kids wanting to make games, the best choice of programming language might be “None”. There are a few engines out there that don’t really require programming. Most of these use a “Lego” approach, where you build logic out of primitive “blocks” that you can drag and connect.

This option is certainly appealing, especially for those that think they can’t “do” programming. And successful games have been made with no-code engines. Retro City Rampage, for example, is a game created in GameMaker, and a number of HTML5 mobile games are being made in Construct2. Some other engines have now started creating their own “no programming required” add-ons, like the Blueprints system of Unreal Engine 4.

The problem comes when you inevitable exceed the limitations of the engine, when you need to do something its designers didn’t include a block for. For children and younger teens, this may never happen, but anyone wanting to go out of the box might need more than they can get from, say, Scratch’s colorful jigsaw pieces. When that happens, some of these engines have a fallback: Construct2 lets you write plugins in JavaScript, while GameMaker has its own language, GML, and the newest version of RPG Maker uses Ruby.

Programming, especially game programming, is hard, there’s no doubt about it. I can understand wanting to avoid it as much as possible. Some people can, and they can make amazing things. If you can work within the limitations of your chosen system, that’s great! If you need more, though, then read on.

JavaScript

Examples: Unity3D, Phaser

JavaScript is everywhere. It’s in your browser, on your phone, and in quite a few desktop games. The main reason for its popularity is almost tautological: JavaScript is everywhere because it’s everywhere. For game programming, it started coming into its own a few years ago, as mobile gaming exploded and browsers became optimized enough to run it at a decent speed. With HTML5, it’s only going to get bigger, and not just for games.

As a language, JavaScript is on the easy side, except for a few gotchas that trip up even experienced programmers. (There’s a reason why it has a book subtitled “The Good Parts”.) For the beginner, it certainly offers the easiest entry: just fire up your browser, open the console, and start typing. Unity uses JS as its secondary language, and about a million HTML5 game engines use it exclusively. If you want to learn, there are worse places to start.

Of course, the sheer number of engines might be the language’s downfall. Phaser might be one of the biggest pure JS engines right now, but next year it could be all but forgotten. (Outside of games, this is the case with web app frameworks, which come and go with surprising alacrity.) On top of that, HTML5 engines often require installation of NodeJS, a web server, and possibly more. All that can be pretty daunting when all you want to do is make a simple game.

Personally, I think JavaScript is a good starting language if you’re careful. Would-be game developers might be better off starting with Unity or Construct2 (see above) rather than something like Phaser, though.

C++ (with a few words on C)

Examples: Unreal Engine 4, SFML, Urho3D

C++ is the beast of the programming world. It’s big, complex, hard to learn, but it is fast. Most of today’s big AAA games use C++, especially for the most critical sections of code. Even many of the high-level engines are themselves written in C++. For pure performance, there’s not really any other option.

Unfortunately, that performance comes at a price. Speaking as someone who learned C++ as his second programming language, I have to say that it’s a horrible choice for your first. There’s just too much going on. The language itself is huge, and it can get pretty cryptic at times.

C is basically C++’s older brother. It’s nowhere near as massive as C++, and it can sometimes be faster. Most of your operating system is likely written in C, but that doesn’t make it any better of a choice for a budding game programmer. In a way, C is too old. Sure, SDL is a C library, but it’s going to be the lowest level of your game engine. When you’re first starting out, you won’t even notice it.

As much as I love C++ (it’s probably my personal favorite language right now), I simply can’t recommend starting with it. Just know that it’s there, but treat it as a goal, an ideal, not a starting point.

Lua

Examples: LÖVE, many others as a scripting or modding language

Lua is pretty popular as a scripting language. Lots of games use it for modding purposes, with World of Warcraft by far the biggest. For that reason alone, it might be a good start. After all, making mods for games can be a rewarding start to game development. Plus, it’s a fairly simple language that doesn’t have many traps for the unwary. Although I’ll admit I don’t know Lua as well as most of the other languages in this list, I can say that it can’t be too bad if so many people are using it. I do get a kind of sense that people don’t take it seriously enough for creating games, though, so take from that what you will.

C#

Examples: Unity3D, MonoGame

C# has to be considered a good candidate for a first language simply because it’s the primary language of Unity. Sure you can write Unity games in JavaScript, but there are a few features that require C#, and most of the documentation assumes that’s what you’ll be using.

As for the language itself, C# is good. Personally, I don’t think it’s all that pretty, but others might have different aesthetic sensibilities. It used to be that C# was essentially Microsoft-only, but Mono has made some pretty good strides in recent years, and some developments in 2015 (including the open-sourcing of .NET Core) show positive signs. Not only that, but my brother finds it interesting (again, thanks to Unity), so I almost have to recommend at least giving it a shot.

The downside of C# for game programming? Yeah, learning it means you get to use Unity. But, that’s about all you get to use. Besides MonoGame and the defunct XNA, C# doesn’t see a lot of use in the game world. For the wider world of programming, though, it’s one of the standard languages, the Microsoft-approved alternative to…

Java

Examples: LibGDX, JMonkeyEngine, anything on Android

Java is the old standard for cross-platform coding. The Java Virtual Machine runs just about anywhere you can think of, even places it shouldn’t (like a web browser). It’s the language of Minecraft and your average Android app. And it was meant to be so simple, anybody could learn it. Sounds perfect, don’t it?

Indeed, Java is simple to learn. And it has some of the best tools in the world. But it also has some of the slowest, buggiest, most bloated and annoying tools you have ever had the misfortune of using. (These sets do overlap, by the way.) The language itself is, in my opinion, the very definition of boring. I don’t know why I feel that way, but I do. Maybe because it’s so simple, a child could use it.

Obviously, if you’re working on Android, you’re going to use Java at some point. If you have an engine that runs on other platforms, you might not have to worry about it, since “native” code on Android only needs a thin Java wrapper that Unity and others provide for you. If you’re not targeting Android, Java might not be on your radar. I can’t blame you. Sure, it’s a good first language, but it’s not a good language. The me from five years ago would never believe I’m saying this, but I’d pick C# over Java for a beginning game developer.

Python

Examples: Pygame, RenPy

I’ll gladly admit that I think Python is one of the best beginner languages out there. It’s clean and simple, and it does a lot of things right. I’ll also gladly admit that I don’t think it can cut it for game programming. I can say this with experience as I have tried to write a 2D game engine in Python. (It’s called Pyrge, and you can find the remnants of it on my Github profile that I won’t link here out of embarrassment.). It’s hard, mostly because the tools available aren’t good enough. Python is a programmer’s language, and Pygame is a wonderful library, but there’s not enough there for serious game development.

There’s always a “but”. For the very specific field of “visual novels”, Python does work. RenPy is a nice little tool for that genre, and it’s been used for quite a few successful games. They’re mostly of the…adult variety, but who’s counting? If that’s what you want to make, then Python might be the language for you, just because of RenPy. Otherwise, as much as I love it, I can’t really recommend it. It’s a great language to learn the art of programming, but games have different requirements, and those are better met by other options.

Engine-Specific Scripting

Examples: GameMaker, Godot Engine, Torque, Inform 7

Some engine developers make their own languages. The reasons why are as varied as the engines themselves, but they aren’t all that important. What is important is that these engine-specific languages are often the only way to interact with those environments. That can be good and bad. The bad, obviously, is that what you learn in GML or GDScript or TorqueScript doesn’t carry over to other languages. Sometimes, that’s a fair trade, as the custom language can better interact with the guts of the engine, giving a performance boost or just a better match to the engine’s quirks. (The counter to this is that some engines use custom scripting languages to lock you into their product.)

I can’t evaluate each and every engine-specific programming language. Some of them are good, some are bad, and almost all of them are based on some other language. Godot’s GDScript, for example, is based on Python, while TorqueScript is very much a derivative of JavaScript. Also, I can’t recommend any of these languages. The engines, on the other hand, all have their advantages and disadvantages. I already discussed GameMaker above, and I think Godot has a lot of promise (I’m using it right now), but I wouldn’t say you should use it because of its scripting language. Instead, learn the scripting language if you like the engine.

The Field

There are plenty of other options that I didn’t list here. Whether it’s because I’m not that familiar with the language, or it doesn’t see much use in game development, or because it doesn’t really work as a first language, it wasn’t up there. So here are some of the “best of the rest” options, along with some of the places they’re used:

  • Swift (SpriteKit) and Objective-C (iOS): I don’t have a Mac, which is a requirement for developing iOS apps, and Swift is really only useful for that purpose. Objective-C actually does work for cross-platform programming, but I’m not aware of any engines that use it, except those that are Apple-specific.

  • Haxe (HaxeFlixel): Flash is dying as a platform, and Haxe (through OpenFL) is its spiritual successor. HaxeFlixel is a 2D engine that I’ve really tried to like. It’s not easy to get into, though. The language itself isn’t that bad, though it may be more useful for porting old Flash stuff than making new games.

  • Ruby (RPG Maker VX Ace): Ruby is one of those things I have an irrational hatred for, like broccoli and reality shows. (My hatred of cats, on the other hand, is entirely rational.) Still, I can’t deny that it’s a useful language for a lot of people. And it’s the scripting language for RPG Maker, when you have to delve into that engine’s inner workings. Really, if you’re not using RPG Maker, I don’t see any reason to bother with Ruby, but you might see things differently.

  • JavaScript variants (Phaser): Some people (and corporations), fed up with JavaScript’s limitations, decided to improve it. But they all went in their own directions, with the result of a bewildering array of languages: CoffeeScript, TypeScript, LiveScript, Dart, and Coco, to name a few. For a game developer, the only one directly of any use is TypeScript, because Phaser has it as a secondary language. They all compile into JS, though, so you can choose the flavor you like.

If there’s anything I missed, let me know. If you disagree with my opinions (and you probably do), tell me why. Any other suggestion, criticism, or whatever can go in the comments, too. The most important thing is to find something you like. I mean, why let somebody else make your decisions for you?

2D Grid Movement with Kinematic Bodies (Godot)

Movement on a grid is common in many games, especially 2D games. In one of my current projects (a “falling blocks” game), this particular problem came up: how do you get grid-based (or discrete) movement on the X-axis while retaining free, continuous movement on the Y-axis? Specifically, I’m using the Godot engine, but the same principle should carry over to any game engine or development environment.

Movement in 2D

Many 2D game engines offer physics systems, and they all tend to be pretty similar (probably because most of them use Box2D under the hood). While your game may be all about sprites, the physics code works with bodies and shapes. Roughly speaking, bodies represent the “mass” of your game objects, while a body’s shapes outline its area. When two bodies’ shapes overlap, there’s a collision, which is handled however your game is supposed to: kill an enemy, take damage from a bullet, etc.

Depending on the specific engine, you have a few different kinds of shapes available. Godot, for example, lets you assign rectangles, circles, lines, “capsules” (like a rectangle with rounded caps on each end), and general polygons. If these aren’t enough, you can combine multiple shapes on a single body. Of course, most 2D engines work this way, so you probably already knew all that.

For bodies, you again have options. Walls and other immobile obstacles are usually static bodies (i.e., they don’t move), and interactive elements are often rigid bodies fully under the influence of physics. The player character, in many engines, is a third type of body, the kinematic body, which causes collisions and stops when it hits a static body, but isn’t affected by forces or friction or, indeed, any physics at all. Once again, though, you already know all of this, because that’s how most 2D physics engines work.

The Setup

For this specific problem, I’m using a kinematic body to represent each falling block. Attached to that body is a sprite (the default Godot icon, for this post) and a collision shape, as you can see in this screenshot:

KinematicBody2D scene tree

(In Godot, there are separate classes for 2D and 3D physics objects, so we have to use KinematicBody2D and CollisionShape2D.)

The kinematic body is the basic object representing each block, the sprite is its appearance, and the collision shape defines its area. Simple enough. Now, what we want to happen is this: move the sprite in two different ways. On the Y-axis, the block should fall down continuously, moving through every point on its way to the bottom. On the X-axis, however, we want the block to “jump” from one position to another, because the blocks have to stack perfectly.

I’ve also set up a scene to use as a base. It’s nothing much, just walls on either side and a floor on the bottom of the screen:

Scene tree for walls and floors

When all this is done, we’ll have a sprite falling from the top of the screen until it hits the “wall” at the bottom. At any point after it appears, you can click and drag it to move it from side to side, and it will stay on a grid, something like this:

Grid movement

Making the Body

We can make the body/sprite/shape combination as follows:

  • The KinematicBody2D is the root node. The only property I changed was reducing the collision margin (Collision > Margin in the Inspector window) to 0.001, the lowest it can go. You don’t actually need to do this for the example, but it may help if you have a problem with collisions detected when bodies aren’t really touching. (There’s also a script attached to this node, but we’ll get to that.)
  • The Sprite is our image. Load the icon.png file that’s included with every Godot project, and you can leave pretty much everything else as is.
  • The CollisionShape2D node, as you might expect, is our collision shape. Due to the way Godot works, we need to define the shape of the shape, which you can do under CollisionShape2D > Shape in the Inspector. Create a new RectangleShape2D in the menu, and set its X and Y extents to something a little less than 32:

RectangleShape2D Properties

(The logo image is 64×64 pixels in size, and extents are measured from the center. If we set the extents to exactly 32, then some blocks might be considered colliding when they really aren’t. That’s because of the collision margin I mentioned above. You can even like 31.999 if you like, and that may work better than 31. Honestly, I’m not sure at the moment.)

The Code

Now that we have all that out of the way, we come to the real meat of the post, the code. Add a new script to your KinematicBody2D node. I named mine gridmove.gd, but you can call it whatever you want. Anyway, here’s the code:

extends KinematicBody2D

# Our accumulated motion on the X axis
var xaccum

# Track if we're dragging a sprite
var mouse_down

# These are the width and height of the sprite
var twidth
var theight

# A default fall speed (like gravity, but velocity instead of acceleration)
const STARTING_SPEED = 100.0

# A velocity vector that we'll use for calculations below
var velocity = Vector2()

func _ready():
    # This object will use input and fixed-timestep physics
    set_process_input(true)
    set_fixed_process(true)

    # Initialize our variables
    xaccum = 0
    twidth = get_node("Sprite").get_texture().get_width()
    theight = get_node("Sprite").get_texture().get_height()
    mouse_down = false
    velocity.y = STARTING_SPEED

func _fixed_process(delta):
    # The object will fall until it hits the bottom of the world or another object
    var motion = velocity * delta

    # Test if we've accumulated enough movement to "jump" one grid square,
    # If we have, then we'll add that much movement to our motion vector.
    if abs(xaccum) > twidth:
        motion.x = twidth * sign(xaccum)
        xaccum -= twidth * sign(xaccum)
    else:
        motion.x = 0

    # Move the object as much as possible
    motion = move(motion)

    # If we're colliding (with the wall or another object), 
    # then we need to modify our motion vector.
    # See the Godot wiki for how and why this works:
    # https://github.com/okamstudio/godot/wiki/tutorial_kinematic_char#problem
    if is_colliding():
        var n = get_collision_normal()
        motion = n.slide(motion)
        move(motion)

    # If the mouse button has been released,
    # we can stop worrying about motion on the X axis
    if not mouse_down:
        xaccum = 0

func _input(event):
    # Create a rectangle covering the entire sprite area
    var gp = get_global_pos()
    gp.x -= twidth/2
    gp.y -= theight/2
    var gr = Rect2(gp, Vector2(twidth, theight))

    # If the left mouse button is pressed while over the object,
    # all we do is set our state variable. If it's released anywhere,
    # we clear that same variable.
    if event.type == InputEvent.MOUSE_BUTTON and event.button_index == 1:
        if gr.has_point(event.pos):
            mouse_down = event.pressed
            get_tree().set_input_as_handled()
        elif mouse_down and not event.pressed:
            mouse_down = false

    # If the user drags while holding the left mouse button,
    # that's our signal to start accumulating motion.
    if event.type == InputEvent.MOUSE_MOTION and mouse_down:
            xaccum += event.relative_x
            get_tree().set_input_as_handled()

The comments tell you most of what’s going on in the code itself. Basically, what we’re doing is “saving up” the motion on the X-axis until it’s enough to move by one grid “square”, which is the width of the logo sprite. The xaccum variable holds how much motion we’ve saved, and we check it each frame (technically, each physics update period, which isn’t necessarily tied to the frame rate). If we’ve saved up enough, then we move the sprite, deducting that motion from our accumulated value.

The added wrinkle is due to gravity, as you can see at the top of the _fixed_process function. Blocks in this particular scene fall at 100 pixels per second, and then they might move on the X-axis. With a vector, we can represent both of these motions, as in line 44, but then we have a problem. Kinematic bodies, remember, can cause collisions when they move, and the move() method stops when the body collides with another, as explained in the wiki article linked on line 49, which also shows how to use the slide() method to change the motion vector.

Spawning the Blocks

The following script should be added to the root Node of the other scene (the one where we defined the walls and floor). All it does is spawn a new block (body, sprite, and shape) whenever you press Space.

extends Node

var block

func _ready():
    set_process_input(true)
    randomize()
    block = load("res://block.xscn")
    spawn(randi() % 10)

func _input(event):
    if event.type == InputEvent.KEY and event.is_pressed() and event.scancode == KEY_SPACE:
        spawn(randi() % 10)

func spawn(column):
    var node = block.instance()
    var tex = node.get_node("Sprite").get_texture()

    # Add 1 to the column value for the left wall,
    # add 0.5 because positions are relative to the center of an object
    var spawn_x = (column + 1.5) * tex.get_width()
    node.set_pos(Vector2(spawn_x, tex.get_height() / 2))
    add_child(node)

Most of this is basic Godot engine stuff like creating a node instance. We do add a hint of uncertainty by spawning each new block in a random grid column.

Conclusion

There’s a lot more that can be done with this code, and it’s probably not bug-free. There may even be a better way of going about this particular problem. If so, I’d love to hear about it! Also, even though I used Godot for this example, the same pattern will work anywhere you have 2D physics, from big names like Unity, to Phaser and other “simpler” engines. You might even be able to adapt it to work in 3D, but I haven’t really tried. Let me know what you come up with, and have fun!

Random Number Distributions (JS)

Last week, I talked about a method for choosing random values within a set, one of the many uses for random numbers in a game. This time, I’ll go deeper into the notion of probability distributions, and how you can make use of them in game development and other kinds of programming. A word of warning: this post will have code (usually Javascript) and might use a lot of math!

Simply Random

The uniform distribution is the one you already know. It’s behind all the simple RNG functions we saw before, like C’s rand() or Javascript’s Math.random(), and it’s what you get when you roll a single die: every number has an equal chance of coming up. In math terms, if there are n possibilities, then the chance of getting any specific one is 1/n. Couldn’t be simpler, really. For most game uses, this is your main tool, and the “weighted set” from the other post is a handy add-on.

The Bell Curve

I mentioned the bell curve and the normal distribution last time, but here I’ll go into a little bit more detail. The bell curve, of course, is often an early introduction to the world of statistics and terms like “standard deviation”, and (as we saw in the other post) it’s what you start getting when you roll more and more dice at a time.

Obviously, that’s one way to get a normal distribution: roll a bunch of dice and add them together:

var dieRoll = function() { return Math.floor(Math.random() * 6) + 1; }
var bellCurveRoll = 0;
for (var i = 0; i < 10; i++) {
    bellCurveRoll += dieRoll();
}

This gives us something close (though not perfect): random numbers will range from 10 to 60, with 35 being the most common. If we need something better (i.e., more accurate), we’ll need to delve into probability theory. Don’t worry, it’s only a short dive.

Side Quest

The mean might be familiar to you, since it’s not much more than another name for “average”. For a normal distribution, the mean is the center point of the curve, the part where it’s at its highest.

Less familiar is the standard deviation, although you may remember that from high school or early college. It’s important in a lot of stats-based fields, because it measures how “clustered” a group of data points is.

Now, for a set of data, you can calculate the mean and standard deviation. That’s pretty much how things like grading curves work: you take the data and make a distribution that fits. For RNGs, however, we have to work backwards. Instead of calculating the mean and standard deviation for the data, we choose them at the start, and our RNG uses them to provide the proper distribution of values. For the normal distribution, this means that about 68% of the values will be within 1 standard deviation of the mean, 95% within 2, and 99.7% within 3. (By the way, the standard deviation is usually identified in math by the Greek letter sigma: σ. “3-sigma” confidence, then, is 99.7% likelihood that something is true. “Six sigma” encompasses everything within 6 standard deviations of the mean, or about 99.9999998%; it’s not quite “one in a billion”, but it’s pretty close.)

Back to Normal

So, knowing all this boring math, you can start getting your random numbers. Here’s one way of doing it in Javascript:

function normalDistribution (mu, sigma) {
    var u1 = Math.random();
    var u2 = Math.random();

    var z0 = Math.sqrt(-2.0 * Math.log(u1)) * Math.cos(Math.PI*2 * u2);
    var z1 = Math.sqrt(-2.0 * Math.log(u1)) * Math.sin(Math.PI*2 * u2);

    return z0 * sigma + mu;
}

This uses a method called the Box-Muller transform to generate a random number on a bell curve. (The astute reader will notice that the function actually generates two random numbers, but throws one of them away. If you like, you can make a better function that stores the second value and returns it as the next random number.) The two parameters are our mean (mu, because it is often written as the Greek letter μ) and the standard deviation (sigma). The Wikipedia link above explains the theory behind this method, as well as giving links to other ways, some of which might be faster.

Exponential Randomness

Normal distributions have their uses, and they’re about as far as most people get in studying randomness. But we won’t stop there. We’ll move on.

Next up is the exponential distribution. This one isn’t that hard to make in code:

function expoDistribution (lambda) {
    return -Math.log(1.0 - Math.random()) / lambda;
}

But you might wonder if it’s really useful. Well, as it turns out, it does come in handy sometimes. Basically, the exponential distribution can be used anywhere you need a “time between events” type of randomness, like random events firing in a strategy game.

The lambda parameter is what’s called a “rate parameter”, and it’s intimately related to the mean; in fact, it’s the reciprocal: the exponential distribution’s mean is 1 / lambda. But what does it mean? Let’s take an example: say you’re making a game where special power-ups appear, on average, twice every minute. Using the above function with lambda as 2, the result would be the time (in minutes) until the next power-up. (The mean would then be 1/2, or 30 seconds, which makes intuitive sense.)

Pareto, Principle, and Power

If you’ve ever heard of the “Pareto Principle” or the “80-20 rule”, then you’ve got a head start on learning about the Pareto distribution. The general idea is thus: there are a few with a lot, and a lot with a little. “The top 20% control 80% of the wealth” is the most common way to state this particular idea, but a random distribution with these properties can be surprisingly useful in games. Here’s the code:

function paretoDistribution (minimum, alpha) {
    var u = 1.0 - Math.random();
    return minimum / Math.pow(u, 1.0 / alpha);
}

We have two parameters we can control this time. minimum is the lowest possible value that can be returned, while alpha controls the “shape” of the distribution. (Generally, higher values of alpha have a faster drop-off, meaning that lower values have higher probability. The “80-20” distribution has an alpha of log(5) / log(4), or about 1.161.)

The Pareto distribution isn’t just used for wealth, though. Anywhere you have a “long tail”, it might be what you’re looking for. Random city sizes (or star sizes, for an interstellar game) follow a Pareto distribution, and it might be a good way to model “loot drops” in an RPG; less powerful objects are far more common than the Ultimate Sword of Smiting, after all.

In Closing

These aren’t all that’s available, but the four distributions I’ve shown are probably the most useful for programmers, especially game developers. As before, I didn’t originally come up with any of this; it’s all been known since before I was born. Some code is converted from Python’s extensive random module, specifically the functions random.expovariate() and random.paretovariate(). The code for the normal distribution is my Javascript conversion of the Box-Muller transform example at the Wikipedia link above. (By the way, if you want me to post examples for a different language, just ask!)

A lot of people already know all this material, and there are plenty of other sites detailing them better than I can, but I hope that this is enough to get you interested.