gpt4 book ai didi

c# - Unity 中的领导者跟随植绒/转向

转载 作者:行者123 更新时间:2023-11-30 18:18:33 29 4
gpt4 key购买 nike

我在 C# 中为我的 unity 项目创建了一个植绒算法。我试着关注 this example ,但问题是把所有东西放在一起,我无法推断。以下代码是我希望拥有一个领导者跟随植绒系统的一部分。

我在基本的三个转向子程序(对齐、凝聚、分离)中添加了跟随/寻求转向,但现在这些机器人只是聚集在领导者的顶部并跟随他。我希望他们跟随领导者,但也保持彼此分离,而不是像他们不合时宜地互相堆积。

当用户选择一组 boid,然后选择它们应该聚集到的位置时,最接近的 boid 被分配为领导者,并被分配到目标的 A* 路径。其他 boid 然后调用 flocking 而不是路径代码。

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;
}

最佳答案

好吧,我有几次尝试类似的东西,如果你想让你的单位与你的领导者有一段距离,只需采用领导者速度并使用那个反向矢量,那个反向矢量将是你的单位目的地,也使用矢量.scale 如果你想自己调整间隔距离。

关于c# - Unity 中的领导者跟随植绒/转向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41165465/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com