我试过关注this example,但问题是把所有的东西都放在一起,而且我无法推断。
我已经在基本的三个转向子例程(对齐,内聚,分离)中添加了跟随/寻求转向,但现在boids只是聚集在leader的顶部并跟踪他。我希望他们跟随领导者的脚步,但也要保持彼此之间的分离,而不是像他们不合拍那样相互堆积。
当用户选择一组boid,然后选择它们应该聚集到的位置时,最近的boid被分配到leader,并被分配到目标的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;
}发布于 2017-02-08 12:26:14
我有几次尝试过类似的方法,如果你想让你的单位和你的领导者保持一段距离,只要取领导者的速度,然后使用反向向量,这个反向向量就是你的单位的目的地,如果你想调整间隔距离,也可以使用vector.scale。
https://stackoverflow.com/questions/41165465
复制相似问题