c# - Unity Ai GameObject 移动时不断提高速度
问题描述
如果玩家存在或不存在,我做了一些代码进行敌人搜索,如果玩家存在去玩家杀死他,代码工作正常,但敌人每移动一次,速度就会保持增加,我不希望速度增加所以如何让它以相同的起始速度移动而不增加任何增加这是我的代码
void Update () {
if (target == null) {
if (!searchingForThePlayer) {
searchingForThePlayer = true;
StartCoroutine (searchForPlayer ());
}
return;
}
if (Vector3.Distance (target.position, transform.position) < 20) {
transform.position = Vector2.MoveTowards (transform.position, target.position, 1f * Time.deltaTime);
if (target.position.x < transform.position.x && !facingRight)
Flip ();
if (target.position.x > transform.position.x && facingRight)
Flip ();
} else {
}
StartCoroutine (UpdatePath ());
}
IEnumerator searchForPlayer () {
GameObject sRusult = GameObject.FindGameObjectWithTag ("Player");
if (sRusult == null) {
yield return new WaitForSeconds (0.5f);
StartCoroutine (searchForPlayer ());
} else {
target = sRusult.transform;
searchingForThePlayer = false;
StartCoroutine (UpdatePath ());
yield return null;
}
}
IEnumerator UpdatePath () {
if (target == null) {
if (!searchingForThePlayer) {
searchingForThePlayer = true;
StartCoroutine (searchForPlayer ());
}
yield return null;
} else {
if (Vector3.Distance (target.position, transform.position) < 20) {
transform.position = Vector2.MoveTowards (transform.position, target.position, 1f * Time.deltaTime);
if (target.position.x < transform.position.x && !facingRight)
Flip ();
if (target.position.x > transform.position.x && facingRight)
Flip ();
} else {
}
}
// Start a new path to the target position, return the result to the OnPathComplete method
yield return new WaitForSeconds (1f / 2f);
StartCoroutine (UpdatePath ());
}
void Flip () {
Vector3 scale = transform.localScale;
scale.x *= -1;
transform.localScale = scale;
facingRight = !facingRight;
}
解决方案
每一帧,在你的Update()
方法中,你都会启动UpdatePath()
协程。然后,在 中UpdatePath()
,您启动另一个UpdatePath()
协程。在任何情况下,您都不会启动它,因此这可以确保它UpdatePath()
永远持续运行。
由于您还不断地在 中开始一个新的Update()
,这意味着您不断堆积越来越多的协程,这意味着游戏运行的次数越多UpdatePath()
,每帧调用的次数就越多。
换句话说,你的物体的速度在技术上并没有增加,它只是MoveTowards()
被调用的时间数量,它确实具有相同的最终结果。
至于修复,我建议重组你的代码。例如,我发现它非常可疑,Update()
并且UpdatePath()
彼此几乎相同。我也觉得它UpdatePath()
在运行结束时开始自己很奇怪。
推荐阅读
- php - 在表单提交失败时保留下拉列表选择/值 - Laravel 6.x
- excel - VBA Excel-将数据更新到另一个工作表
- unix - 如何使用 ps 和 grep 显示 PID<100 的进程?
- amazon-web-services - terraform 12 每个
- python - 将 Facebook Graph API 洞察 JSON 转换为 pandas 数据框
- python - Python Pandas groupby 使用另一个数据框中的值而不使用 for 循环
- python - 出现错误:在 Keras 中加载模型时:
- android - Google Play 上不再提供 Android 应用
- delphi - 在运行时填充 ListView
- html - 从另一个组件访问一个组件的方法