c# - Unity,MoveTowards 工作很奇怪
问题描述
好吧,我有带有“敌人”标签的游戏对象,我像这样收集它们:
enemies = GameObject.FindGameObjectsWithTag("Enemy");
之后,我试图移动第一个“敌人”:
int newPositionX;
int newPositionY;
bool targetReached = false;
int moveSpeed = 1;
void Update()
{
if (!targetReached)
{
newPositionX = Mathf.FloorToInt(enemies[0].transform.position.x)-1;
newPositionY = Mathf.FloorToInt(enemies[0].transform.position.y);
enemies[0].transform.position = Vector3.MoveTowards(enemies[0].transform.position,
new Vector3(newPositionX, newPositionY), moveSpeed * Time.deltaTime);
targetReached = true;
}
if (Vector3.Distance(enemies[0].transform.position, new Vector3(
newPositionX, newPositionY)) < 0.1f)
{
targetReached = false;
}
}
但是“敌人”没有采取任何行动。如果删除以下内容,我可以对其进行编辑:
targetReached = true;
“敌人”正在移动,但我无法阻止它。这让我觉得应该在更新中永久调用MoveTowards函数?
解决方案
MoveTowards 返回一个向量,它将游戏对象向目标方向移动一步。
另外,我不确定这一点,但是查看您的代码,将 targetReached 设置为 false 的 if 语句仅在 targetReached 已经为 false 时运行,因此您可能希望将其放在 if (!targetReached) 语句中
推荐阅读
- timeout - weblogic 12C 中的 JTA 超时问题
- c# - 对于某些客户端,ASP.NET Core 3.1 SignalR 连接在 2 分钟后重新连接
- reactjs - 无法将故事书中的道具作为材质 UI 变体传递
- android - 如何在 android 模拟器中使用网络摄像头?
- python - UnboundLocalError 当两个面出现在输入
- matlab - Matlab - 尝试高斯拟合的各种起点,选择具有最高 rsquare 的起点,然后绘制
- ocaml - 将项目附加到 Ocaml 中的列表时出现语法错误
- machine-learning - pyspark.sql.utils.IllegalArgumentException:'字段“功能”不存在
- python - 我有一个 N*M 字符矩阵,我试图在整个矩阵中找到最常见的字符,但它只计算最后一行
- python - 如何在加载增量训练的`tensorflow.keras.model`时强制执行特定的signature_map?