监视目标敌人和轨道

时间:2018-11-04 20:55:18

标签: unity3d

以前,我有一个脚本,可以查看玩家,但只能在按下Tab键但无法循环穿过敌人或其他任何物体时使用。整日都在寻找答案,我决定这会很棒,我现在可以找到标记了敌人的东西并通过它们循环,但是我一直无法找到一种方法来观察敌人并保持注视并能够绕他们转一圈。

public class debug : MonoBehaviour
 {

 public List<Transform> targets;
 public Transform selectedTarget;
 public string targetTag = "Enemy";
 private Transform myTransform;

 //Use this for initialization
 void Start()
 {
     targets = new List<Transform>();
     selectedTarget = null;
     myTransform = transform;
     AddAllEnemies();
 }

 public void AddAllEnemies()
 {
     GameObject[] go = GameObject.FindGameObjectsWithTag(targetTag);
     foreach (GameObject enemy in go)
     {
         AddTarget(enemy.transform);
     }
 }

 public void AddTarget(Transform enemy)
 {
     targets.Add(enemy);
 }

 /*private void SortTargetsByDistance()
 {
     targets.Sort(delegate (Transform t1, Transform t2) {
         return (Vector3.Distance(t1.position, myTransform.position).CompareTo)
             (Vector3.Distance(t2.position, myTransform.position));
     });
 } */
 private void SortTargetsByDistance()
 {
     targets.RemoveAll(target => target == null);
     targets.Sort(delegate (Transform t1, Transform t2) {
         return (Vector3.Distance(t1.position, myTransform.position).CompareTo)
             (Vector3.Distance(t2.position, myTransform.position));
     });
 }

 private void TargetEnemy()
 {
     if (selectedTarget == null)
     {
         SortTargetsByDistance();
         selectedTarget = targets[0];
     }
     else
     {
         int index = targets.IndexOf(selectedTarget);
         if (index < targets.Count - 1)
         {
             index++;
         }
         else
         {
             index = 0;
         }

         selectedTarget = targets[index];
     }
 }

 //Update is called once per frame
 void Update()
 {
     if (Input.GetKeyDown(KeyCode.Tab))
     {
         TargetEnemy();
     }
     }
 }

我正在无效更新中尝试使用transform.LookAt(TargetEnemy);,但收到一条错误消息,提示无法从方法组转换为转换。我真的坚持了这一点,感谢您的帮助。

编辑:我是个大笨蛋,我改而使用transform.LookAt(selectedTarget);,瞬间的角色将转身看着敌人。现在,我需要让玩家一直看着目标并在目标周围移动。

2 个答案:

答案 0 :(得分:1)

Transform.LookAt

您需要将其传递给Transform,而不是void

TargetEnemy();
transform.LookAt(selectedTarget);

或者,您可以使TargetEnemy()返回Transform。:

private Transform TargetEnemy()
 {
     /* stuff */

     return selectedTarget;
 }
transform.LookAt(TargetEnemy());

答案 1 :(得分:1)

您好,感谢所有关注的人,并感谢@ SonicBlue22的回答。我在几个小时后就弄清楚了。

    void Update()
    {
        if (Input.GetKeyUp(KeyCode.Tab))
        {
            TargetEnemy();
            transform.LookAt(selectedTarget);
        }

        if (selectedTarget != null)
        {
            transform.LookAt(selectedTarget);
        }

        if (Input.GetKeyUp(KeyCode.Q))
        {
            selectedTarget = null;
            return;
        }

    }

}