在恢复追逐你之前,如何让敌人AI离开你一定距离。 C#Unity

时间:2018-06-17 03:21:21

标签: c# unity3d artificial-intelligence navmesh

我有这个代码让敌人追逐玩家。

当玩家被击中时,我希望敌人跑40个单位,然后继续追逐玩家。

我所拥有的代码并没有使敌人运行40个单位,它只会让敌人在很短的距离内运行,然后它会立即恢复追逐。我知道我必须添加一个“if”来检查敌人是否已经运行了40个单位才让他们再次追逐玩家但我不知道该如何去做。

谢谢。

using UnityEngine;
using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class EnemyMovementWithDamage : MonoBehaviour {
  public GameObject ThePlayer;
  public float TargetDistance;
  public float AllowedDistance = 2;
  public GameObject TheEnemy;
  public int AttackTrigger;
  public RaycastHit Shot;

  private NavMeshAgent agent;
  private NavMeshPath path;

  public float goalDistance = 40f;

  void Start() {
    path = new NavMeshPath();
    agent = GetComponent<NavMeshAgent>();
  }

  void Update() {
    transform.LookAt (ThePlayer.transform);
    if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), out Shot)) {
        TargetDistance = Shot.distance;
        }

    if (AttackTrigger == 0) {

        if (TargetDistance > AllowedDistance)
        {
        agent.SetDestination(ThePlayer.transform.position);
      }
    }

    if (TargetDistance <= AllowedDistance){
        if (AttackTrigger == 1) {
            Vector3 target = transform.position + Vector3.forward * goalDistance;
            agent.SetDestination(target);
            Debug.Log("hit");
            //Here is only runs away for a small period then resumes chasing the player. 
            //I want the Chacacter to run away until it reaches its goal distance of 40f then start chasing again.

    }
    }

  }

  void OnTriggerEnter() {
    AttackTrigger = 1;
  }

  void OnTriggerExit() {
    AttackTrigger = 0;
  }

}

0 个答案:

没有答案