首页 > 解决方案 > 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函数?

标签: c#unity3dvectorpositionmove

解决方案


MoveTowards 返回一个向量,它将游戏对象向目标方向移动一步。

另外,我不确定这一点,但是查看您的代码,将 targetReached 设置为 false 的 if 语句仅在 targetReached 已经为 false 时运行,因此您可能希望将其放在 if (!targetReached) 语句中


推荐阅读