如何在跟随随机路径时避免使用对象? Unity 2d

时间:2018-04-18 03:28:48

标签: c# unity3d path-finding

我有一个敌人对象设置为在2d迷宫环境中向随机节点移动。我唯一的问题就是让敌人不要像蟑螂一样挤过碰撞墙。这是我从教程中遵循的代码,用于通过点数移动敌人。所有的帮助都表示赞赏,自从我试图绕过这个问题以来已经差不多一个星期了!

    public class Enemy_AI : MonoBehaviour {

     public float speed;
     public float waitTime;
     public float startWaitTime;

     public Transform[] moveSpots;
     private int randomSpot;

     private void Start()
     {
         randomSpot = Random.Range(0, moveSpots.Length);
         waitTime = startWaitTime;
     }

     void Update()
     {
         transform.position = Vector2.MoveTowards(transform.position, moveSpots[randomSpot].position, speed * Time.deltaTime);

         if(Vector2.Distance(transform.position, moveSpots[randomSpot].position) < 0.2f)
         {
             if(waitTime <= 0)
             {
                 randomSpot = Random.Range(0, moveSpots.Length);
                 waitTime = startWaitTime;
             }

             else
             {
                 waitTime -= Time.deltaTime;
             }

         }

     }

 }

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

为此你应该使用Raycast,光线投射可以检测给定位置和方向之间是否有物体,你也可以传递光线的长度以及应该考虑哪些物体层。

请记住,您的代码可能类似于以下内容:

public LayerMask mask;
 void Update()
 {

     RaycastHit2D hit = Physics2D.Raycast(transform.position, moveSpots[randomSpot].position, 0.2f, mask);
     if(!hit)
     {
        transform.position = Vector2.MoveTowards(transform.position, moveSpots[randomSpot].position, speed * Time.deltaTime);

     }
     if(Vector2.Distance(transform.position, moveSpots[randomSpot].position) < 0.2f)
     {
         if(waitTime <= 0)
         {
             randomSpot = Random.Range(0, moveSpots.Length);
             waitTime = startWaitTime;
         }

         else
         {
             waitTime -= Time.deltaTime;
         }

     }   
    }

使用检查器中的蒙版,您可以选择将用作光线中的碰撞的元素,以便您的&#34;障碍&#34;应该在那里标记(并有自己的图层)

如果有任何移动的地方可以进行调试,你可以这样做:

if(Vector2.Distance(transform.position, moveSpots[randomSpot].position) < 0.2f)
{
// as it is
}
else
{
    bool canMove = false;
    for(int i = 0; i < moveSpots.Lenght;i++)
    {
       if(Vector2.Distance(transform.position, moveSpots[i].position) < 0.2f)
       {
           canMove = true;
       }
    }
    Debug.Log("Is avaliable any move?" + canMove);
}