我为统一项目在C#中创建了植绒算法。我尝试遵循this example,但问题是将所有内容组合在一起,并且无法推断。以下代码是我希望拥有一个领导者跟随植绒系统的一部分。
我在基本的三个转向子例程(对齐,内聚,分离)中添加了跟随/寻找转向功能,但是现在,这些辫子只是聚集在领导者的上方,并遮蔽了他。我希望他们跟随领导者,但也要保持彼此分离,而不是像彼此异相一样只是彼此叠加。
当用户选择一组Boid,然后选择将其聚集到的位置时,最接近的Boid将被分配前导并为目标分配A *路径。然后,其他投标人调用植绒而不是路径代码。
void Update()
{
if (flock.Count > 0 &&
flockLeader != gameObject)
{
Flocking();
}
else
{
Movement();
}
}
private void Flocking()
{
Vector3 vector = Vector3.zero, alignment = Alignment(), cohesion = Cohesion(), separation = Separation(), following = Following();
int weightAlignment = 1, weightCohesion = 1, weightSeparation = 1, weightFollowing = 1;
NeighbourhoodWatch(); // determine neighbour boids (exclude self)
vector += (separation * weightSeparation);
vector += (alignment * weightAlignment);
vector += (cohesion * weightCohesion);
vector += (following * weightFollowing);
vector.Normalize();
if (!vector.Equals(Vector3.zero))
{
if (Vector3.Angle(vector, transform.forward) >= 1f)
{
transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(transform.forward, vector, rateOfTurn * Time.deltaTime, 0.0f));
}
else // rotate and move
{
transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(transform.forward, vector, rateOfTurn * Time.deltaTime, 0.0f));
transform.Translate(Vector3.forward * (speed * Time.deltaTime));
}
}
}
private Vector3 Alignment()
{
Vector3 vector = Vector3.zero;
if (neighbourhood.Count > 0)
{
foreach (GameObject boid in neighbourhood)
{
vector += boid.transform.forward;
}
vector /= neighbourhood.Count;
}
return vector;
}
private Vector3 Cohesion()
{
Vector3 vector = Vector3.zero;
if (neighbourhood.Count > 0)
{
foreach (GameObject boid in neighbourhood)
{
vector += boid.transform.position; // acquire centre of mass
}
vector /= neighbourhood.Count;
vector = vector - transform.position; // direction to centre of mass
}
return vector;
}
private Vector3 Separation()
{
Vector3 vector = Vector3.zero;
if (neighbourhood.Count > 0)
{
int spaceInvaders = 0;
foreach (GameObject boid in neighbourhood)
{
float proximity = Vector3.Distance(boid.transform.position, transform.position);
if (proximity <= footprint)
{
vector += boid.transform.position - transform.position;
spaceInvaders++;
}
}
if (spaceInvaders > 0)
{
vector /= spaceInvaders;
vector *= -1; // negation (invert direction)
}
}
return vector;
}
private Vector3 Following()
{
Vector3 vector = Vector3.zero;
vector = flockLeader.transform.position - transform.position;
return vector;
}
最佳答案
好吧,我有一些时间尝试与此类似的操作,如果您想让单位与领导者保持一定距离,只需采用领导者的速度并使用该反向矢量,该反向矢量将成为您的单位Destination,也可以使用vector.scale您想调整自己的间隔距离。