我在为我的鼻咽癌设置AI时遇到了麻烦。我想让它在我地图上的随机点周围走动,当玩家靠近时,它就会跑开。当我追逐我的npc时,转义的虫子很好,但是当我停下来的时候,它们会向玩家的方向和向后弹,而不是仅仅设置另一个目的地…
这是代码。我将runToRandomLocation()放在Update()方法中。
void runAway()
{
if (!isDead)
{
transform.position = Vector2.MoveTowards(transform.position, player.transform.position, -movementSpeed * 1.5f * Time.deltaTime);
}
}
void runToRandomLocation()
{
if (!isDead) {
if (Vector2.Distance(transform.position, player.transform.position) > 3) // if player is not near
{
if (Vector2.Distance(transform.position, randomDestination) <= 2) // when NPC is close to destination he sets another
{
randomDestination = new Vector2(Random.Range(-11, 11), Random.Range(-5, 5));
}
else
{
transform.position = Vector2.MoveTowards(transform.position, randomDestination, movementSpeed * Time.deltaTime); // NPC is just walking from point to point
}
}
else
{
runAway(); // if player is near
}
}
}发布于 2019-02-17 02:27:05
仅当到达以前的目的地时,才会生成新的随机目的地。这里似乎发生的事情是,在NPS逃得足够远之后,它将继续移动到它在逃跑之前拥有的最后一个随机目的地,因此它将返回。可能是在玩家的方向上。因此,在一帧之后,它再次靠近玩家,并再次跑开。然后在循环中再次返回到旧的目的地,依此类推。你需要做的只是在运行完away.For后重新生成随机目的地,你需要一些状态机,就像@退休忍者指出的那样,但它实际上是一个非常原始的状态机。例如,下面这样的代码应该是有效的:
private bool onTheRun = false;
void regenDestination() {
randomDestination = new Vector2(Random.Range(-11, 11), Random.Range(-5, 5));
}
void runAway() {
if (!isDead) {
transform.position = Vector2.MoveTowards(transform.position, player.transform.position, -movementSpeed * 1.5f * Time.deltaTime);
onTheRun = true;
}
}
void runToRandomLocation() {
if (!isDead) {
if (Vector2.Distance(transform.position, player.transform.position) > 3) // if player is not near
{
if (onTheRun)
{
regenDestination();
onTheRun = false;
}
if (Vector2.Distance(transform.position, randomDestination) <= 2) // when NPC is close to destination he sets another
{
regenDestination();
} else {
transform.position = Vector2.MoveTowards(transform.position, randomDestination, movementSpeed * Time.deltaTime); // NPC is just walking from point to point
}
} else {
runAway(); // if player is near
}
}
}https://stackoverflow.com/questions/54725542
复制相似问题