Simple boids like collision prevention for rigidbodies

edited in General
So I just wanted to start adding something to the community that has been helping me for nothing in return. I have relatively little programming experience, and I found that most boids tutorials was a tad complex for me to implement.
I stumbled upon this neato script for planetary gravity simulation(/http://www.unifycommunity.com/wiki/index.php?title=Gravity) and modified it to work as a collision avoiding system for rigidbodies (Unity3d). Remember to read the the licence thingy (link at the bottom of the unifycommunity page).

This is my slightly modified version:

private var range : float;

function Start()
{
	//making the random range for pushing to start at
	// I found that a larger range takes a hit on performance
	range = Random.Range(3, 10);
}

function FixedUpdate () {
    var cols : Collider[] = Physics.OverlapSphere
    (transform.position, range);
    var rbs : Array = new Array();
    for (c=0;c<cols.length;c++) {
    	//the 'spine1' part makes shure 
        //it only effects the groups of enemies
        if (cols[c].attachedRigidbody != rigidbody
        && cols[c].name == "Spine1") {
            var breaking :boolean = false;
            for (r=0;r<rbs.length;r++) {
                if (cols[c].attachedRigidbody == rbs[r]) {
                    breaking=true;
                    break;
                }
            }
            if (breaking) continue;
            rbs.Add(cols[c].attachedRigidbody);
            var offset : Vector3 = (transform.position - 
            cols[c].transform.position);
            var mag: float = offset.magnitude;
            //added a '-' and random push strength
            cols[c].attachedRigidbody.AddForce(-offset/mag/mag *
            Random.Range(60, 110));
        }
    }
}


This script, like the original, is available to anyone under this licence : http://creativecommons.org/licenses/by-sa/3.0/
All you have to do is apply this script to the rigidbodies you want to avoid collisions with each other. Then change the name to what you named the rigid bodies. I used this to spread the enemies in Fling Fu out a bit.

I hope this is semi useful to some people :).

If however it is useless information or a bad way of achieving the goal, don't hesitate to speak up.
I'd also be glad to improve my methods if anyone has any hints or tips.

Thanks everyone for being an awesome community! :D




Sign In or Register to comment.