Simple Behaviour Trees for your game in Javascript and C#

A little while ago I tried to understand what Behaviour Trees are about, as in a couple of games I’m developing I have sets of NPCs that I have to manage and I would like to somehow decouple their behaviour from the main game flow. Here you can find a good explanation of behaviour trees.

Sample behaviour tree

Sample behaviour tree

Got this, I searched for implementations (I wanted both Javascript and C# implementations) and I didn’t like them because of the amount of code and classes required. Then on StackOverflow I found this very simple example:

Stack Overflow simple behaviour trees

Encouraged by this,  with Matteo Bicocchi we started writing our own implementations, as I simply could not believe that the code needed to be so complex 😉 . We first wrote the Javascript implementation, and the two main points we had to deal with have been:

1. Distinguish between the tree description and the instance tree being run: you need a concrete instance as you need to be independent of “tick” speed and need to be able for each instance to find what is the current node.

2. You need to handle single node completion asynchronously e.g. if you have a “chase” node, this may take a long time to resolve.

Now we have our implementation, its very simple code and can be useful in a wide variety of game development situations – surely its not a complete solution but it works fine.

Here is a simple Js Fiddle example you can play with directly in the browser.

Fiddle with behaviour trees

and here are full sources in both Javascript and C# on GitHub. The C# code is a simple port from Javascript, surely it could be refined (branch it!). It also contains two classes making the C# example run, its made with a for Unity (extends MonoBehaviour) but the code can be used anywhere.

The code is mostly commented in the Javascript version.

Follow me on Twitter where I post about game design, game development, Unity3d 2D, HTML5, applied games.

Social Share Toolbar

Comments

  1. pietro says:

    Just added in C#: SelectorWeightedRandomArrayNode, which is probably one of the most useful nodes (idea came from practical example): you want your NPC to pick a random choice in a set, but some actions should be more likely than others. E.g.
    A Lazy around 0.7
    B Pretend to work 0.2
    C Actually work 0.1
    Notice that you must have A+B+C = 1.

  2. Xananax says:

    This is really interesting and I’m looking forward to using it!
    On a side note, the link to the jsFiddle is wrong (got the right one from the github page)

Speak Your Mind

*