Unity:随机NavMesh代理速度C#?

时间:2017-02-21 06:21:42

标签: c# unity3d

我有Enemy预制件,有navmesh代理。敌人由向下脚本控制,如何使用给定脚本

随机使用navmesh代理速度

敌人运动

public class EnemyMovement : MonoBehaviour
{
    Transform player;               // Reference to the player's position.
    PlayerHealth playerHealth;      // Reference to the player's health.
    EnemyHealth enemyHealth;        // Reference to this enemy's health.
    UnityEngine.AI.NavMeshAgent nav;

    void Awake ()
    {
        player = GameObject.FindGameObjectWithTag ("Player").transform;
        playerHealth = player.GetComponent<PlayerHealth>();
        enemyHealth = GetComponent <EnemyHealth> ();
        nav = GetComponent <UnityEngine.AI.NavMeshAgent> ();
    }


    void Update ()
    {
        // If the enemy and the player have health left...
        if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
        {
            // ... set the destination of the nav mesh agent to the player.
            nav.SetDestination (player.position);
        }
        // Otherwise...
        else
        {
            // ... disable the nav mesh agent.
            nav.enabled = false;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

使用UnityEngine.Random.Range(yourMinf, yourMax5f);获取随机数。

将该号码分配给NavMeshAgent.speed

例如,下面的代码段会在25之间分配随机速度。

nav.speed = UnityEngine.Random.Range(2f, 5f);

将其放入if声明中。您可能还对其他变量感兴趣,例如NavMeshAgent.angularSpeedNavMeshAgent.acceleration