- Home /
This post has been wikified, any user with enough reputation can edit it.
Question by
Ebamber · Dec 05, 2013 at 10:22 PM ·
javascriptinstantiatevector3artificial intelligence
Help with my Flocking Algorithm
@HideInInspector var averagepos : Vector3;
@HideInInspector var keepaway : Vector3;
@HideInInspector var matchvel : Vector3;
var raptor : GameObject;
var raptorarray : GameObject[];
function Start () {
}
function Update () {
raptorarray= GameObject.FindGameObjectsWithTag(raptor.tag);
if ( raptorarray.length == 1)
return;
else
{
for (var l = 0;l<raptorarray.length;l++)
transform.position = transform.position + rule1(raptorarray[l]) + rule2(raptorarray[l]) + rule3(raptorarray[l]);
}
}
function rule1(rap : GameObject) //keep to the average position of the flock
{
var pos : Vector3 ;
for (var i= 0; i<raptorarray.length;i++)
{
pos+=raptorarray[i].transform.position;
}
averagepos=pos/raptorarray.Length;
return averagepos/100;
}
function rule2(rap : GameObject) //avoid other objects including others in the flock
{
var away : Vector3;
for (var i= 0; i<raptorarray.length;i++)
{
var distance :float = Vector3.Distance(rap.transform.position, raptorarray[i].transform.position);
if (distance < 1)
keepaway = rap.transform.position + (rap.transform.position - raptorarray[i].transform.position);
}
return keepaway;
}
function rule3(rap : GameObject) //match the velocity of the others in the flock
{
for (var k=0; k<(raptorarray.length);k++)
{
for (var i= 0; i<(raptorarray.length-1);i++)
{
if(rap.rigidbody.velocity != raptorarray[i].rigidbody.velocity)
{
rap.rigidbody.velocity+= raptorarray[i].rigidbody.velocity;
rap.rigidbody.velocity/=2;
}
}
}
matchvel=rap.rigidbody.velocity/8;
return matchvel;
}
I pasted all the code because I don't know exactly where my problem is. Basically when one enemy spawns on his own everything's fine, but as soon as the next one spawns, they both disappear and I get the error message "transform.position assign attempt for 'Enemy 1(Clone)' is not valid. Input position is { 244941330874883540000000000000000000000.000000, 13465854283936009000000000000000000000.000000, Infinity }. UnityEngine.Transform:set_position(Vector3) Flocking:Update() (at Assets/Flocking.js:20)"
I get the feeling there's something wrong with my rule1 procedure but I'm not discounting the possibility of the others being buggy too. Can somebody please help?
Comment