Flocking Code

Has anyone written any flocking/boids code in Unity JS yet?

Hi,

shouldn’t there be a lot of sources on the net about boids?!

I would be surprised if you can’t find a Javascript implementation. At least there are for sure a lot of Java sources out there.

For a start i would go to Reynolds site Boids (Flocks, Herds, and Schools: a Distributed Behavioral Model) or just google for one try Boids

Regards,

taumel

Yeah, there’s tons out there. In fact, I used the resources you mention (amongst other) when I wrote my Director flocking behaviors.

I was hoping maybe the OTEE elves might be convinced to write a Unity demo or maybe even put some flocking in their AI components.

Hint, hint …

Well, i guess in the end maybe with V2 (not the german rocket! ;O) there will be some AI involved and so maybe also some work building on the open steering behaviours.

But if you need them now it’s also not hard to implement them. There also is a nice diploma thesis around with full java source and an editor via http://fbim.fh-regensburg.de/~saj39122/feisch/Diplomarbeit/index.html

But obviously much more work than just click&use. And that’s what we prefer, right?! ;O)

Not sure if this is useful, but here’s a Blender Python script for “swarming”:

http://www.alienhelpdesk.com/index.php?id=42

I have done the steering behaviours, but I haven’t done flocking yet. I plan to get to it at somepoint when I have time.

The actual steering behaviours required are quite easy to write (seperation, cohesion, alignment). The “trick” is partitioning it all so it will actually run fast with a lot of boids.

For steering behaviours, all you are doing is making your own velocity vectors every frame and applying that vector to your agent.

Here is the basic Seek behaviour:

public Vector3 Seek(Vector3 position, Vector3 target, float maxSpeed)
    {
        Vector3 tempDir = target - position;
        steeringVelocity = tempDir.normalized * maxSpeed;
 
        return steeringVelocity;
    }

All you do is pass the returned vector to the agent’s rigidbody velocity or if you dont want to use rigidbodies, just update the position every frame like this:
position += velocity * Time.deltaTime;

After that, it is just figuring out the other behaviours you want (arrive, wander, flee, evade, pursuit, etc). It can get more complex with different locomotion systems though.

-Jeremy

After a bit of googeling I have come across this open source C++ lib for steering behavious. Prehaps there are some C++ gurus who can whip this up into a Unity plugin ?
http://opensteer.sourceforge.net/

I have a simple flocking script (restricts objects to a 3D box, or follows the screen cursor) in Javascript that an associate used in another engine. I haven’t had the time to try to port it to Unity yet, but when I do, I’ll post here also.

Sweet!

Thanks, BigK!

This page has a pretty succinct explanation of how to do boids; using it I was able to get a pretty nice swarm of angry bondage wasps going in a few hours in BlitzMax. While getting the hang of BlitzMax.

(I’m playing with moving said wasps into other frameworks because Blitz’s 2d renderer starts to bog down with >70 or so objects, and its OpenGL renderer’s documents are just ‘go read a book on OpenGL’. Once I figure out how to tell Unity ‘here’s a set of objects, let me scavenge through them for information’, I’ll probably have a swarm of abstracted insects in no time.)

Very cool Egypt, welcome to Unity, I think you’ll like it here. :slight_smile:

I was given some code written in Javascript for another engine that apparently worked. Not sure if it’s useful and I’ve been swamped with work so don’t have any time to dig through it. It’s not my code so I’m reluctant to just post it on the forum, but if someone else wants to look at it and promisses to share when they’re done, drop me an email.

Would love to see a swarming script in Unity, just no time to touch it right now…

Hey, at least I won’t have to write my own furshlugginer joystick configuration wizard like I did in Blitz yesterday.

The flocking code I threw together in Blitz earlier this week weighs in at about 100 lines, including whitespace, comments, and a little bit of rudimentary laser-shooting code that went in for convenience’s sake. It’s not a complicated thing to do once I figure out the proper Unity-ism for “for each boid in boids[ ]”.

Actually, that’s basically it.

http://unity3d.com/Documentation/ScriptReference/Array.html

Mostly it’s getting the array of boids. Looks like FindGameObjectsWithTag() is the way to go.

You could go with FindGameObjectsWithTag(), but the boid-script will probably be Instantiate()'ing the boids, so you might as well just populate your array as you create them.

As for using full game-objects, that’s fine of course, but another technique which could be interesting for instect swarms, is to use particle systems. For this, check the particle system docs to see how to create and control particles:

http://unity3d.com/Documentation/ScriptReference/ParticleEmitter.html

Have fun in your explorations.

d.

This is the result of a few hours getting repeatedly lost in Unity’s docs. It’s a lot slower than I was hoping - I suspect I may be missing something fundamental in How Unity Wants To Work!

Make a box to hold your swarm, turn off the rendering, and attach this script to it. Drop a prefab object that will be your boid onto the script and start it running. Tweak settings as you like.

I didn’t bother rotating the boids to face their direction because my intended usage is very abstracted.

23089–823–$swarm_113.js (2.99 KB)

var someCheckbox = false;

Very cool first attempt. It took a bit of playing around with the settings to get a feel for what is going on, but very cool.

In addition to the things listed in the remarks for things to add, it would be great to be able to fix the orientation of the boids, so birds always have their wings horizontal and point in the direction they are flying.

Very nice though. Thanks for sharing!

You have a pretty heavy inner loop going over all the transforms, asking for their positions and velocities and doing it order n squared.

So you really want to make sure all your data is nicely packed together and you do no function calls into the Unity runtime during the order n squred loop. Instead you just have a single lookup into one of the arrays. This way all your data is nicely cached. All in one place and very fast.

So instead of getting the position order n squared times, Just calculate them once in the update function, store them in an array, also store the velocity. Then do all the calculations and apply the calculations to the rigidbody

Something to get your started:

	var boidPositions = new Vector3[transform.childCount];
	var boidVelocity = new Vector3[transform.childCount];
	
	var i = 0;
	var boidCount = transform.childCount;
	for (var boid : Transform in transform) {
		boidPositions[i] = boid.position;
		boidVelocity[i] = boid.rigidbody.velocity;
		i++;
	}
	
	for (i=0;i<boidCount;i++)
	{
		var v1 = clump(i, boidPositions, boidVelocity) * clumping;
                 ....
	}

I’ve done a quite modified and optimized version of this code and put it in the wiki:

http://www.unifycommunity.com/wiki/index.php?title=Flocking

I’ve also attached the file.

I used the physics engine and sphere colliders to keep the boids apart. It’s faster than writing your own collision code.

They will follow a target and have a random motion factor.

Have fun.

(updated with bugfix in camera code)

49022–1807–$flockingunitypackagev2_184.zip (989 KB)